在 pandas 条形图中设置 xticks

2024-05-15

我在下面的第三个示例图中遇到了这种不同的行为。为什么我能够正确编辑 x 轴的刻度pandas line() and area()情节,但不与bar()?修复(一般)第三个示例的最佳方法是什么?

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()

Problem:

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

您可以看到,通过在轴上使用普通的 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())

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

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]))

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

解决方案:

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

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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 pandas 条形图中设置 xticks 的相关文章

随机推荐