Python 为什么使用datetime.striptime()转换matplotlib的日期时不会显示整个日期
更新: 添加如下代码以解决问题Python 为什么使用datetime.striptime()转换matplotlib的日期时不会显示整个日期,python,csv,matplotlib,plot,Python,Csv,Matplotlib,Plot,更新: 添加如下代码以解决问题 import matplotlib.dates as mdates fig.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m/%d')) fig.gca().xaxis.set_major_locator(mdates.DayLocator()) '''this for minor ticks''' fig.gca().xaxis.set_minor_formatter(mdates.DateF
import matplotlib.dates as mdates
fig.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m/%d'))
fig.gca().xaxis.set_major_locator(mdates.DayLocator())
'''this for minor ticks'''
fig.gca().xaxis.set_minor_formatter(mdates.DateFormatter('%Y/%m/%d'))
fig.gca().xaxis.set_minor_locator(mdates.WeekdayLocator(mdates.MONDAY))
'''disabled major and minor overlapping'''
fig.gca().xaxis.remove_overlapping_locs = False
或:
plt.xticks(天,[i.date()表示以天为单位的i])
========================================================================
我在做这本书后面的练习,当我使用datetime.strtime()
转换matlibplot中.csv
文件的日期时,它不会在x轴上显示整个日期
例如,列表中的转换日期为[2014-07-012014-07-02,…,2014-07-31]列表中总共32个
但最后,当我在matpltlib中绘制它时,它只在x轴上显示[2014-07-012014-07-052014-07-092014-07-13]
为什么不显示整个日期?我可以修改它吗
代码如下:
import csv
from matplotlib import pyplot as plt
from datetime import datetime
filename='sitka_weather_07-2014.csv'
with open(filename,'r') as f,open('xx.csv','w') as w:
content=csv.reader(f,delimiter=',',quotechar='"')
'''shift to title'''
header=next(content)
days,temps=[],[]
for value in content:
'''value[0] for the Date'''
a=datetime.strptime(value[0],'%Y/%m/%d')
days.append(a)
'''value[1] for Temp'''
b=int(value[1])
temps.append(b)
print(len(days))
#>> 31 #here is 32 days in list
fig=plt.figure(figsize=(10,6))
font={'weight':'normal',
'color':'cyan',
'fontsize':24,
}
plt.title('Weather',fontdict=font)
plt.xlabel('Date',fontdict=font)
plt.ylabel('Temperature',fontdict=font)
fig.autofmt_xdate()
for x,y in zip(days,temps):
plt.text(x,y+0.1,y,ha='center',va='bottom',fontsize=8,color='red')
plt.plot(days,temps,marker='o',mfc='red',mec='None')
plt.show()
通常
matplotlib
不会显示所有标签(如果有),因为它看起来很凌乱。如果要显示所有日期,可以添加以下行:
plt.xticks(your_full_list_of_dates)
以上:
plt.show()
也可用于样式设置。类似于为什么它不显示y轴上的每个数字。。。它将显示尽可能多的有用的记号。您可以使用
DayLocator
显示每天,或者使用HourLocator
显示每小时等fig.gca().xaxis.set_major\u formatter(mdates.DateFormatter('%Y/%m/%d'))
和fig.gca().xaxis.set_major\u locator(mdates.DayLocator())
非常有用!当我使用plt.xticks(days)
来显示所有的日期时,似乎有些错误,x轴标签不是日期。@M_Sea:datetime.strtime
returndatetime
对象-它不超过日期也保存一天中的时间(小时、分钟等)。如果未给出一天中的时间,则假定为午夜(00:00:00
)。您需要提取日期本身以用作标签。只需执行:plt.xticks(天,[i.date()表示以天为单位的i])
其中days
是datetime
类型对象的列表。