python - 在 Pandas 条形图中设置 xticks

标签 python pandas matplotlib

我在下面的第三个示例图中遇到了这种不同的行为。为什么我可以使用 pandas line()area() 绘图正确编辑 x 轴的刻度,但不能使用 酒吧()?修复(一般)第三个示例的最佳方法是什么?

import numpy as np
import pandas as pd
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt

x = np.arange(73,145,1)
y = np.cos(x)

df = pd.Series(y,x)
ax1 = df.plot.line()
ax1.xaxis.set_major_locator(ticker.MultipleLocator(10))
ax1.xaxis.set_minor_locator(ticker.MultipleLocator(2.5))
plt.show()

ax2 = df.plot.area(stacked=False)
ax2.xaxis.set_major_locator(ticker.MultipleLocator(10))
ax2.xaxis.set_minor_locator(ticker.MultipleLocator(2.5))
plt.show()

ax3 = df.plot.bar()
ax3.xaxis.set_major_locator(ticker.MultipleLocator(10))
ax3.xaxis.set_minor_locator(ticker.MultipleLocator(2.5))
plt.show()

最佳答案

问题:

条形图旨在与分类数据一起使用。因此,这些条实际上并不位于 x 的位置,而是位于 0,1,2,...N-1 的位置。然后将条形标签调整为 x 的值。
如果您随后仅在每 10 个柱上打勾,则第二个标签将放置在第 10 个柱上,依此类推。结果是

enter image description here

您可以看到,通过在轴上使用普通的 ScalarFormatter,条形图实际上定位在从 0 开始的整数值处:

ax3 = df.plot.bar()
ax3.xaxis.set_major_locator(ticker.MultipleLocator(10))
ax3.xaxis.set_minor_locator(ticker.MultipleLocator(2.5))
ax3.xaxis.set_major_formatter(ticker.ScalarFormatter())

enter image description here

现在你当然可以像这样定义你自己的固定格式化程序

n = 10
ax3 = df.plot.bar()
ax3.xaxis.set_major_locator(ticker.MultipleLocator(n))
ax3.xaxis.set_minor_locator(ticker.MultipleLocator(n/4.))
seq =  ax3.xaxis.get_major_formatter().seq
ax3.xaxis.set_major_formatter(ticker.FixedFormatter([""]+seq[::n]))

enter image description here

它的缺点是它从某个任意值开始。

解决方案:

我想最好的通用解决方案是根本不使用 pandas 绘图函数(无论如何它只是一个包装器),而是直接使用 matplotlib bar 函数:

fig, ax3 = plt.subplots()
ax3.bar(df.index, df.values, width=0.72)
ax3.xaxis.set_major_locator(ticker.MultipleLocator(10))
ax3.xaxis.set_minor_locator(ticker.MultipleLocator(2.5))

enter image description here

关于python - 在 Pandas 条形图中设置 xticks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43478659/

相关文章:

python - PLY yacc解析IF-ELSE IF-ELSE嵌套语句

python - Pandas, Python : rotate some (31-day) columns of a dataframe and match them to the existing (year, 月)行(NOAA 数据)

python - 将 requests.get() 输出解析为 Pandas 数据框

python - 如何使用 matplotlib 从 numpy 列表中绘制多个数据集

Python fig.text() - 检索文本的高度以进行对齐

python - 如何在 Python 中解析 Linux 终端错误消息?

python - Choregraphe中的python代码错误

python - 如何从 Python 中的生成器函数一次获取一个值?

Python:如何从 Pandas 图中叠加 2 个条形图

matplotlib - 在 Mayavi 体积可视化中使用感知均匀的色彩图