无法在matplotlib x轴上显示dateindex

2024-09-28 23:37:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从pandas数据帧构建x轴为dateIndexmatplotlib图表。我试图模仿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()

enter image description here


Tags: importapipandasdatematplotlibasaxdates
2条回答

您可以使用pd.DataFrame.plot来处理其中的大部分

df = pd.DataFrame(dict(
    y1=y1, y2=y2
), index=x)

df.plot()

enter image description here

问题如下。pd.date_range(start='4/1/2012', periods=len(y1))创建从2012年4月1日到2012年7月9日的日期。
现在将主定位器设置为YearLocator。这意味着,您希望在轴上每年都有一个记号。但是,所有日期都在2012年的同一年内。因此在绘图范围内没有显示主要刻度。你知道吗

建议改为使用MonthLocator,这样每个月的第一个就被勾选。另外,如果使用格式设置器是有意义的,它实际上显示月份,例如'%b %Y'。如果您愿意,您可以使用DayLocator作为小记号来显示每天的小记号。你知道吗

ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
ax.xaxis.set_minor_locator(mdates.DayLocator())

完整示例:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

y1 = np.arange(100)*0.14+1
y2 = -(np.arange(100)*0.04)+12

x = 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(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
ax.xaxis.set_minor_locator(mdates.DayLocator())

fig.autofmt_xdate()
plt.show()

enter image description here

相关问题 更多 >