[英]X-axis Plot with Matplotlib
The code is running ok but on the X axis
the date is not showen compelety as it described in the dictionary(it shows on the plot just hours:minute:second
). 该代码运行正常,但是在
X axis
日期未如字典中所描述的那样显示完整(在图上仅显示hours:minute:second
)。
how can I show the complete date ( year:month:day hours:minute:second
)? 如何显示完整的日期(
year:month:day hours:minute:second
)?
Code: 码:
import numpy as np
import matplotlib.pyplot as plt
import time
from datetime import datetime, timedelta
EQ = {'2017-08-23 02:04:00':(18,1),'2017-08-23 02:05:00':(20,2),'2017-08-23 02:06:00':(12,3),'2017-08-23 02:07:00':(22,4)}
LIST_P=[];Time_P=[]
for j_p in EQ.keys():
LIST_P.append(EQ[j_p][1])
Time_P.append(time.mktime(time.strptime(j_p, "%Y-%m-%d %H:%M:%S")))
dateconv=np.vectorize(datetime.fromtimestamp)
Date_F1=dateconv(Time_P)
fig1 = plt.figure(1)
ax1 = plt.gca()
ax1.plot_date(Date_F1,LIST_P,'g-')
ax1.set_ylabel('Y-axis',fontsize=14)
ax1.set_xlabel('X-axis',fontsize=14)
ax1.grid(True)
for label in ax1.xaxis.get_ticklabels():
label.set_rotation(45)
plt.show()
You need to add ax1.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
to specify the format. 您需要添加
ax1.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
以指定格式。 Consider below code: 考虑下面的代码:
import numpy as np
import matplotlib.pyplot as plt
import time
from datetime import datetime, timedelta
import matplotlib.dates as mdates
EQ = {'2017-08-23 02:04:00':(18,1),'2017-08-23 02:05:00':(20,2),'2017-08-23 02:06:00':(12,3),'2017-08-23 02:07:00':(22,4)}
LIST_P=[];Time_P=[]
for j_p in EQ.keys():
LIST_P.append(EQ[j_p][1])
Time_P.append(time.mktime(time.strptime(j_p, "%Y-%m-%d %H:%M:%S")))
dateconv=np.vectorize(datetime.fromtimestamp)
Date_F1=dateconv(Time_P)
fig1 = plt.figure(1)
ax1 = plt.gca()
ax1.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
ax1.plot_date(Date_F1,LIST_P,'g-')
ax1.set_ylabel('Y-axis',fontsize=14)
ax1.set_xlabel('X-axis',fontsize=14)
ax1.grid(True)
for label in ax1.xaxis.get_ticklabels():
label.set_rotation(45)
plt.show()
Output: 输出:
I suggest to use DateFormatter of matplotlib.dates, adding the following: 我建议使用matplotlib.dates的DateFormatter,添加以下内容:
1) In the beginning: from matplotlib.dates import DateFormatter 1)开始:从matplotlib.dates导入DateFormatter
2) Before ax1.plot_date: myFmt = DateFormatter("%Y-%m-%d %H:%M:%S") ax1.xaxis.set_major_formatter(myFmt) 2)在ax1.plot_date之前:myFmt = DateFormatter(“%Y-%m-%d%H:%M:%S”)ax1.xaxis.set_major_formatter(myFmt)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.