【发布时间】:2020-08-05 04:29:43
【问题描述】:
我希望从 2016-01 到 2020-01(每半年的间隔)的 x 值是“yyyy-mm”。但是,尝试了很多方法,x 值仍然一团糟。
我的代码如下:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import matplotlib.dates as mdates
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
df = pd.read_csv('fcc-forum-pageviews.csv',index_col='date')
df = df[(df['value'] >= df['value'].quantile(0.025)) & (df['value'] <= df['value'].quantile(0.975))]
fig = plt.figure()
fig.set_figwidth(15)
fig.set_figheight(9)
ax = fig.add_subplot(1,1,1)
ax.set_title('Daily freeCodeCamp Forum Page Views 5/2016-12/2019')
ax.set_xlabel('Date')
ax.set_ylabel('Page Views')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax.plot(df['value'],color='r')
数据集可以从here下载。非常感谢任何帮助。
经过@r-beginners的帮助,我更新了代码如下:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import matplotlib.dates as mdates
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
df = pd.read_csv('fcc-forum-pageviews.csv',index_col='date')
df = df[(df['value'] >= df['value'].quantile(0.025)) & (df['value'] <= df['value'].quantile(0.975))]
df.index = pd.to_datetime(df.index)
fig = plt.figure()
fig.set_figwidth(15)
fig.set_figheight(9)
ax = fig.add_subplot(1,1,1)
ax.set_title('Daily freeCodeCamp Forum Page Views 5/2016-12/2019')
ax.set_xlabel('Date')
ax.set_ylabel('Page Views')
ax.set_xticks(range(len(df.index)))
ax.set_xticklabels(range(len(df.index)))
months = mdates.MonthLocator(interval=6)
months_fmt = mdates.DateFormatter('%Y-%m')
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(months_fmt)
ax.plot(df['value'], color='r')
现在它可以以 6 个月的间隔显示 x 值。但是,它不是从 2016-07(数据框的日期)开始,而是从 1970-02 开始。有什么提示吗?谢谢。
【问题讨论】:
标签: python pandas dataframe matplotlib