Python 使用Matplotlib打印多索引数据框时x轴标签出错
我有一个timeseries数据框,我从datetime列计算了一个季节列。然后,我按“季节”和“年份”索引数据帧,并希望绘制结果。代码如下:Python 使用Matplotlib打印多索引数据框时x轴标签出错,python,pandas,matplotlib,Python,Pandas,Matplotlib,我有一个timeseries数据框,我从datetime列计算了一个季节列。然后,我按“季节”和“年份”索引数据帧,并希望绘制结果。代码如下: import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates dates = pd.date_range('20070101',periods=1000) df = pd.DataFrame(np.rand
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
dates = pd.date_range('20070101',periods=1000)
df = pd.DataFrame(np.random.randn(1000), columns =list ('A'))
df['date'] = dates
def get_season(row):
if row['date'].month >= 3 and row['date'].month <= 5:
return 'spring'
elif row['date'].month >= 6 and row['date'].month <= 8:
return 'summer'
elif row['date'].month >= 9 and row['date'].month <= 11:
return 'autumn'
else:
return 'winter'
df['Season'] = df.apply(get_season, axis=1)
df['Year'] = df['date'].dt.year
df.loc[df['date'].dt.month == 12, 'Year'] += 1
df = df.set_index(['Year', 'Season'], inplace=False)
df.head()
fig,ax = plt.subplots()
df.plot(x_compat=True,ax=ax)
ax.xaxis.set_tick_params(reset=True)
ax.xaxis.set_major_locator(mdates.YearLocator(1))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
plt.show()
我只想把年份作为x轴标签,而不是年份和季节
我肯定这很简单,我做错了,但我不知道是什么
编辑:
更改df.plot函数稍微更好地绘制日期,但仍然绘制月份,我更希望只绘制年份,但这比以前稍微好一些
新代码:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
dates = pd.date_range('20070101',periods=1000)
df = pd.DataFrame(np.random.randn(1000), columns =list ('A'))
df['date'] = dates
def get_season(row):
if row['date'].month >= 3 and row['date'].month <= 5:
return 'spring'
elif row['date'].month >= 6 and row['date'].month <= 8:
return 'summer'
elif row['date'].month >= 9 and row['date'].month <= 11:
return 'autumn'
else:
return 'winter'
df['Season'] = df.apply(get_season, axis=1)
df['Year'] = df['date'].dt.year
df.loc[df['date'].dt.month == 12, 'Year'] += 1
df = df.set_index(['Year', 'Season'], inplace=False)
df.head()
fig,ax = plt.subplots()
df.plot(x='date', y = 'A', x_compat=True,ax=ax)
将熊猫作为pd导入
将numpy作为np导入
将matplotlib.pyplot作为plt导入
将matplotlib.dates导入为mdates
日期=pd.日期范围('20070101',期间=1000)
df=pd.DataFrame(np.random.randn(1000),columns=list('A'))
df['date']=日期
def get_季节(世界其他地区):
如果第['date'].month>=3行,第['date'].month=6行,第['date'].month=9行,第['date'].month>=9行,不幸的是,pandas
和matplotlib
时间定位器/格式化程序之间的婚姻永远不会幸福。最一致的方法是将日期时间数据放在datetime
的numpy
数组中,并将其直接绘制在matplotlib
中pandas
确实提供了一个很好的。to_pydatetime()
方法:
fig,ax = plt.subplots()
plt.plot(dates.to_pydatetime(), df.A)
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
yearsFmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
我不清楚你到底想在这里做什么。您的代码运行时没有错误(但不会绘制任何XTICK)。如果我删除了三行ax.xaxis…
代码,代码仍在运行,并且我得到的XTICK标记为(2007,冬季)、(2007,夏季)
等。请始终包含完整的错误回溯,而不仅仅是最后一行。@cel cheers,编辑为包含完整的错误回溯error@tom抱歉,我只是想把年份作为标签显示,不是季节和年份-Q编辑以显示这一点我想你自己已经做到了-当我获取你的第二个代码块并添加前一个代码中的三行ax.xaxis.set...
时,我得到了你想要的。
fig,ax = plt.subplots()
plt.plot(dates.to_pydatetime(), df.A)
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
yearsFmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)