在熊猫条形图中设置 xticks

PDR*_*DRX 4 python matplotlib pandas

我在下面的第三个示例图中遇到了这种不同的行为。为什么我可以使用pandas line()area()绘图正确编辑 x 轴的刻度,但不能使用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()
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 6

问题:

条形图旨在与分类数据一起使用。因此,条形实际上不是在 的位置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())
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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

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]))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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

解决方案:

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

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))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明