使用 matplotlib 进行 xtick 格式化 - 每年显示的每周数据

xtick formatting with matplotlib - weekly data shown annually

我希望有办法解决这个问题,因为在 pyplot 中有很多关于 xtick 格式的问题,但我还没有找到任何解决这个问题的方法。

我有以下代码:

fig, ax=plt.subplots(1,1,figsize=[10, 5]) # Set dimensions for figure
plt.plot(organic_search.groupby('week-year').Amount.sum(), color='g')
plt.title('Organic Search Revenue Time Series')
fmt = '${x:,.0f}'
tick = mtick.StrMethodFormatter(fmt)
ax.yaxis.set_major_formatter(tick)
plt.ylabel('Revenue')
plt.xlabel('Week')
plt.grid(True)
plt.show()

一切正常,但输出有点乱,因为这是每周数据。

一些示例数据:

Week | Week_Start_Date |  Amount |  year |     week-year |
Week 1      2018-01-01   42920     2018     Week 1 2018
Week 2      2018-01-08   37772     2018     Week 2 2018
Week 3      2018-01-15   41076     2018     Week 3 2018
Week 4      2018-01-22   38431     2018     Week 4 2018
Week 5      2018-01-29  101676     2018     Week 5 2018

输出:

xticks 标签是不可读的,我想知道是否有人知道如何拥有相同的每周图表,但 xticks 只代表年份。我尝试了几种不同的方法,但要么 (1) 它将图形缩小到屏幕的最左侧,要么 (2) 我收到一条错误消息,实际上是“刻度标签 (4) 与数据点 (186) 不匹配”。

我只是想要一个更整洁的显示 - 对分析不重要,但感谢帮助

import pandas as pd
import matplotlib.pyplot as plt
import pandas_datareader as web  # for test data; not part of pandas

# load 1 year of sample data
df = web.DataReader('amzn', data_source='yahoo', start='2020-01-01', end='2021-01-01').reset_index()

# display(df.head())
        Date     High      Low    Open    Close   Volume  Adj Close
0 2020-01-02  1898.01  1864.15  1875.0  1898.01  4029000    1898.01
1 2020-01-03  1886.20  1864.50  1864.5  1874.97  3764400    1874.97

# if the 'Date' column or a date index is not a datetime dtype then convert it
# df.index = pd.to_datetime(df.index)
df.Date = pd.to_datetime(df.Date)

# set the Date column as the index, if it isn't already there
df = df.set_index('Date')

# resample to a Weekly beginning on Monday; .sum() can be used, .mean() is correct for this sample data
dfr = df.resample('W-MON').mean()

# display(dfr.head())
               High      Low     Open    Close      Volume  Adj Close
Date                                                                 
2020-01-06  1895.97  1862.88  1866.50  1891.95  3951733.33    1891.95
2020-01-13  1909.53  1887.02  1901.82  1894.87  3270940.00    1894.87

# plot; plot a single column with y='High'
ax = dfr.plot(y=['High', 'Low'], figsize=(10, 5), grid=True, title='Weekly Resampled Mean High / Low Price', ylabel='Price')
ax.yaxis.set_major_formatter('${x:,.0f}')
plt.show()