gpt4 book ai didi

pandas - Pandas 条形图中的刻度标签重叠

转载 作者:行者123 更新时间:2023-12-05 01:00:05 26 4
gpt4 key购买 nike

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

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

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

default line chart with nice tick labels

但是切换到条形图却造成了这种困惑:

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

bar chart with overlapping tick labels

然后我直接使用 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])

bar chart with arbitrarily placed tick labels

以下是强度系列的摘录:

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

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

enter image description here

相比之下,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()

enter image description here

关于pandas - Pandas 条形图中的刻度标签重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50675920/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com