我试图从pandas数据帧构建x轴为dateIndex
的matplotlib
图表。我试图模仿matplotlib的一些例子,但没有成功。xaxis记号和标签永远不会出现。你知道吗
我认为matplotlib可能没有正确地消化pandas索引,所以我用matplotlibdate2num
帮助函数将其转换为序号,但得到了相同的结果。你知道吗
# https://matplotlib.org/api/dates_api.html
# https://matplotlib.org/examples/api/date_demo.html
import datetime as dt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook
import matplotlib.dates as mpd
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
yearsFmt = mdates.DateFormatter('%Y')
majorLocator = years
majorFormatter = yearsFmt #FormatStrFormatter('%d')
minorLocator = months
y1 = np.arange(100)*0.14+1
y2 = -(np.arange(100)*0.04)+12
"""neither of these indices works"""
x = pd.date_range(start='4/1/2012', periods=len(y1))
#x = map(mpd.date2num, pd.date_range(start='4/1/2012', periods=len(y1)))
fig, ax = plt.subplots()
ax.plot(x,y1)
ax.plot(x,y2)
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
datemin = x[0]
datemax = x[-1]
ax.set_xlim(datemin, datemax)
fig.autofmt_xdate()
plt.show()
您可以使用
pd.DataFrame.plot
来处理其中的大部分问题如下。
pd.date_range(start='4/1/2012', periods=len(y1))
创建从2012年4月1日到2012年7月9日的日期。现在将主定位器设置为
YearLocator
。这意味着,您希望在轴上每年都有一个记号。但是,所有日期都在2012年的同一年内。因此在绘图范围内没有显示主要刻度。你知道吗建议改为使用
MonthLocator
,这样每个月的第一个就被勾选。另外,如果使用格式设置器是有意义的,它实际上显示月份,例如'%b %Y'
。如果您愿意,您可以使用DayLocator
作为小记号来显示每天的小记号。你知道吗完整示例:
相关问题 更多 >
编程相关推荐