【问题标题】:Tick labels overlap in pandas bar chart熊猫条形图中的刻度标签重叠
【发布时间】:2018-11-13 12:20:00
【问题描述】:

TL;DR:在 pandas 中,如何绘制条形图以使其 x 轴刻度标签看起来像折线图?

我制作了一个间隔均匀的时间序列(每天一个项目),并且可以像这样很好地绘制它:

intensity[350:450].plot()
plt.show()

但是切换到条形图造成了这种混乱:

intensity[350:450].plot(kind = 'bar')
plt.show()

然后我直接使用 matplotlib 创建了一个条形图,但它缺少 pandas 的漂亮日期时间序列刻度标签格式化程序:

def bar_chart(series):
    fig, ax = plt.subplots(1)
    ax.bar(series.index, series)
    fig.autofmt_xdate()
    plt.show()

bar_chart(intensity[350:450])

以下是强度系列的摘录:

intensity[390:400]

2017-03-07    3
2017-03-08    0
2017-03-09    3
2017-03-10    0
2017-03-11    0
2017-03-12    0
2017-03-13    2
2017-03-14    0
2017-03-15    3
2017-03-16    0
Freq: D, dtype: int64 

我可以全力以赴,完全手动创建刻度标签,但我宁愿不必婴儿 matplotlib 让 pandas 完成它的工作,并做它在第一个图中所做的事情,但使用条形图.那我该怎么做呢?

【问题讨论】:

    标签: pandas matplotlib


    【解决方案1】:

    Pandas 条形图是分类图。他们为每个类别创建一个刻度(+标签)。如果类别是日期并且这些日期是连续的,则可能旨在将某些日期排除在外,例如仅绘制每五个类别,

    ax = series.plot(kind="bar")
    ax.set_xticklabels([t if not i%5 else "" for i,t in enumerate(ax.get_xticklabels())])
    

    相比之下,matplotlib 条形图是数字图。在这里可以应用一个有用的代码,它可以每周、每月或任何需要的日期打勾。

    此外,matplotlib 允许完全控制刻度位置及其标签。

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    from matplotlib import dates
    
    index = pd.date_range("2018-01-26", "2018-05-05")
    series = pd.Series(np.random.rayleigh(size=100), index=index)
    
    plt.bar(series.index, series.values)
    plt.gca().xaxis.set_major_locator(dates.MonthLocator())
    plt.gca().xaxis.set_major_formatter(dates.DateFormatter("%b\n%Y"))
    plt.show()
    

    【讨论】:

    • 要精确复制刻度线,我想你还需要plt.gca().xaxis.set_minor_locator(dates.WeekdayLocator())
    • 解释概念,给出例子,包括图片。还有一个有用的评论。 10/10 会再问一次,谢谢!
    猜你喜欢
    • 2017-09-20
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 2021-03-10
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    相关资源
    最近更新 更多