【问题标题】:Pandas matplotlib plotting, irregularities in time series labels between bar graph and line graphPandas matplotlib 绘图,条形图和折线图之间时间序列标签的不规则性
【发布时间】:2016-06-24 06:33:37
【问题描述】:

在通过 pandas 使用 matplotlib 创建条形图和折线图时,我遇到了一些不一致的行为。例如:

import matplotlib.pyplot as plt
import pandas as pd
from pandas_datareader import data

test_df = data.get_data_yahoo('AAPL', start='2015-10-01')
test_df['Adj Close'].plot()

使用合理的 x 轴标签按预期绘制:

但是,如果您随后尝试从与条形图相同的数据框中绘制一些东西:

test_df['Volume'].plot(kind='bar')

x 轴刻度标签不再自动识别。

这是 pandas/matplotlib 的预期行为吗?以及如何轻松地将条形图上的 x 轴刻度标签校正为与上面折线图中的相似?

【问题讨论】:

    标签: python matplotlib plot graph


    【解决方案1】:

    你可以告诉 matplotlib 显示每第 N 个标签:

    # show every Nth label
    locs, labels = plt.xticks()
    N = 10
    plt.xticks(locs[::N], test_df.index[::N].strftime('%Y-%m-%d'))
    

    import matplotlib.pyplot as plt
    import pandas as pd
    from pandas_datareader import data
    
    test_df = data.get_data_yahoo('AAPL', start='2015-10-01')
    fig, ax = plt.subplots(nrows=2)
    test_df['Adj Close'].plot(ax=ax[0])
    test_df['Volume'].plot(kind='bar', ax=ax[1])
    
    # show every Nth label
    locs, labels = plt.xticks()
    N = 10
    plt.xticks(locs[::N], test_df.index[::N].strftime('%Y-%m-%d'))
    
    # autorotate the xlabels
    fig.autofmt_xdate()
    plt.show()
    

    产量


    另一种选择是直接使用matplotlib:

    import matplotlib.pyplot as plt
    import pandas as pd
    from pandas_datareader import data
    import matplotlib.dates as mdates
    
    df = data.get_data_yahoo('AAPL', start='2015-10-01')
    fig, ax = plt.subplots(nrows=2, sharex=True)
    
    ax[0].plot(df.index, df['Adj Close'])
    ax[0].set_ylabel('price per share')
    
    ax[1].bar(df.index, df['Volume']/10**6)
    ax[1].xaxis.set_major_locator(mdates.MonthLocator(bymonthday=-1))
    xfmt = mdates.DateFormatter('%B %d, %Y')
    ax[1].xaxis.set_major_formatter(xfmt)
    ax[1].set_ylabel('Volume (millions)')
    
    # autorotate the xlabels
    fig.autofmt_xdate()
    plt.show()
    

    【讨论】:

    • 谢谢,此外,是否可以仅在 x 轴上绘制月份、年份(如 2015 年 10 月),以及如何使 y 轴可读?
    • 您希望 y 标签的外观如何?
    • 实际上可能相同,只是没有 1e8 和 y 轴标签中的回报规模(即交易量(百万))?
    • 我添加了第二个示例,直接使用 matplotlib。有趣的是,sharex=True 在第二个示例中有效,但在使用 pandas DataFrame.plot 调用时无效。
    猜你喜欢
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    相关资源
    最近更新 更多