【问题标题】:xtick formatting with matplotlib - weekly data shown annually使用 matplotlib 格式化 xtick - 每年显示的每周数据
【发布时间】:2021-10-22 19:01:30
【问题描述】:

我希望有办法解决这个问题,因为在 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

输出:

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

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

【问题讨论】:

    标签: python pandas matplotlib graph time-series


    【解决方案1】:
    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()
    

    【讨论】:

    • 成功了。我实际上有一个日期已经格式化为日期时间。我通过了它来代替字符串,这就成功了。谢谢!!
    • @Dilly_Dilly 不客气。很高兴它对你有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 2016-02-11
    相关资源
    最近更新 更多