代码运行正常,但在X axis
上,日期并没有像字典中所描述的那样显示出来(它只显示在情节hours:minute:second
上)。
如何显示完整日期(year:month:day hours:minute:second
)?
代码:
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()
答案 0 :(得分:0)
您需要添加ax1.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
来指定格式。
请考虑以下代码:
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()
输出:
答案 1 :(得分:-1)
我建议使用matplotlib.dates的DateFormatter,添加以下内容:
1)一开始: 来自matplotlib.dates导入DateFormatter
2)在ax1.plot_date之前: myFmt = DateFormatter("%Y-%m-%d%H:%M:%S") ax1.xaxis.set_major_formatter(myFmt)