Python 为什么我的x轴是';s日期是否显示为过去的40年?
我从Python 为什么我的x轴是';s日期是否显示为过去的40年?,python,pandas,matplotlib,Python,Pandas,Matplotlib,我从pytrends模块获取了两个搜索词(banana bread和pumpkin bread)的简单时间序列数据: %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates from pytrends.request import TrendReq pytrends = TrendReq(hl='en-US', tz=240) # requ
pytrends
模块获取了两个搜索词(banana bread
和pumpkin bread
)的简单时间序列数据:
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from pytrends.request import TrendReq
pytrends = TrendReq(hl='en-US', tz=240)
# requests the data from pytrends, which returns a DataFrame
kw_list = ['banana bread', 'pumpkin bread']
pytrends.build_payload(kw_list, timeframe='today 5-y', geo='US')
df = pytrends.interest_over_time()
last_two_years = df['2017-10-01': '2020-10-01']
last_two_years.head()
熊猫似乎感觉到了一年中的美好时光
last_two_years.index[0].year
2017
但是,当我尝试在x轴上用一个月刻度来绘制数据时,我得到了以下曲线图:
ax = last_two_years.plot(figsize=(20, 5))
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=1))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%B, %Y"))
plt.gcf().autofmt_xdate() # rotates the date labels
Jul
一再潜入那里如果您有任何见解,我将不胜感激。我尝试在不使用pytrends的情况下重现上述示例,但一切都很顺利
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
two_years = pd.date_range(start='2017-01-01', end='2019-01-01')
# randomly generated dummy data
data1 = np.random.randn(len(two_years))
data2 = np.random.randn(len(two_years))
ts1 = pd.Series(data=data1, index=two_years)
ts2 = pd.Series(data=data2, index=two_years)
data = {'banana bread': ts1, 'pumpkin bread': ts2}
df = pd.concat(data, axis=1)
数据看起来是一样的
df.head()
banana bread pumpkin bread
2017-01-01 -0.711772 -0.782613
2017-01-02 -0.513398 0.478608
2017-01-03 0.768380 0.286899
2017-01-04 0.073636 1.296839
2017-01-05 -0.408765 -0.828802
大熊猫仍然能正确地识别年份
df.index[0].year
2017
但这一次x轴标签按预期工作
ax = df.plot(figsize=(20, 5))
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=1))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%B, %Y"))
plt.gcf().autofmt_xdate() # rotates the date labels
如果将来有人遇到这种情况,并且正在使用
pytrends
模块,这可能是问题的原因。MPL 3.3.0和pandas datetime存在问题,但应在3.3.1中修复。如果您对最近的matplotlib仍有问题,请打开一个带有可复制示例的错误报告。@JodyKlymak感谢您的回复!我使用的是matplotlib 3.3.2和pandas 1.1.3。我应该打开一个bug报告吗?也许?你能先把上面的例子完整完整吗?@JodyKlymak当然!我用Jupyter笔记本上的所有东西更新了这个例子。如果你不使用外部库,你会得到更多人的帮助。你能做一个假的数据集来做这个吗?
ax = df.plot(figsize=(20, 5))
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=1))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%B, %Y"))
plt.gcf().autofmt_xdate() # rotates the date labels