2016-02-26 48 views
2

我想和matplotlib陰謀,看起來像這樣:Matplotlib和Python:如何從給定的字符串格式化日期時間?

screenshot

的問題是,我從MySQL獲取數據和日期是一個字符串,因此。我想給每個y值分配一個日期。當前的日期格式是這樣的:Y-M-d h:m:s

你能幫我解釋一下如何將其格式化爲有效的日期時間,或者可以在x軸上繪製字符串並在y軸上浮動嗎?

回答

3

通常情況下,最好先將您的數據轉換爲datetime格式。然後,可使用DateFormatter格式如下:

import matplotlib 
import matplotlib.pyplot as plt 
from datetime import datetime 

x_orig = ['2015-12-29 15:01:25', '2015-12-29 15:02:08', '2015-12-29 15:02:13', '2015-12-29 15:04:18'] 
x = [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in x_orig] 
y = ['7.1', '7.4', '9.4', '10.2'] 

xs = matplotlib.dates.date2num(x) 
hfmt = matplotlib.dates.DateFormatter('%Y-%m-%d\n%H:%M:%S') 

fig = plt.figure() 
ax = fig.add_subplot(1,1,1) 
ax.patch.set_facecolor('lightgrey') 
ax.xaxis.set_major_formatter(hfmt) 
ax.set_title('Titel des Reports') 
ax.set_xlabel('datum') 
ax.set_ylabel('2MTemperatur') 
plt.setp(ax.get_xticklabels(), size=8) 
ax.plot(xs, y, linewidth=2) 
ax.scatter(xs, y) 
plt.grid() 
plt.show() 

這會給你以下幾點:

matplotlib screenshot

+0

謝謝這正是我搜索 – frankenapps

相關問題