【问题标题】:How can I set the x-axis tick locations for a bar plot created from a pandas DataFrame?如何为从 pandas DataFrame 创建的条形图设置 x 轴刻度位置?
【发布时间】:2015-12-05 11:17:15
【问题描述】:

我有一个简单的情节,x 标签为 1、1.25、1.5、1.75、2 等,最多 15 个:

该图是从 pandas.DataFrame 创建的,但未指定 xtick 间隔:

speed.plot(kind='bar',figsize=(15, 7))

现在我希望 x 间隔的增量为 1 而不是 0.25,因此标签将读取 1、2、3、4、5 等。

我确信这很容易,但我终其一生都无法弄清楚。

我找到了plt.xticks(),这似乎是正确的电话,但也许是set_xticks

到目前为止,我已经大量更改了 x 刻度,但没有做我想做的事情。任何帮助将不胜感激。

【问题讨论】:

  • 你是如何创作这个情节的?
  • 我使用 pandas DF,speed.plot(kind='bar',figsize=(15, 7)) 制作,但没有对 xtick 间隔做出任何规定

标签: python pandas matplotlib


【解决方案1】:

如果您的 x-label 具有数值,pandas 处理条形图的 x-ticks 的方式可能会非常令人困惑。让我们举个例子:

import pandas as pd
import numpy as np

x = np.linspace(0, 1, 21)
y = np.random.rand(21)
s = pd.Series(y, index=x)

ax = s.plot(kind='bar', figsize=(10, 3))
ax.figure.tight_layout()

您可能希望刻度位置与x 中的值直接对应,即 0、0.05、0.1、...、1.0。但是,情况并非如此:

print(ax.get_xticks())
# [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20]

相反,pandas 根据x 中每个元素的indices 设置刻度locations,然后根据x 设置刻度labels x:

中的
print(' '.join(label.get_text() for label in ax.get_xticklabels()))
# 0.0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0.55 0.6 0.65 0.7 0.75 0.8 0.85 0.9 0.95 1.0

因此,直接设置刻度位置(使用ax.set_xticks)或将xticks= 参数传递给pd.Series.plot() 不会给您预期的效果:

new_ticks = np.linspace(0, 1, 11)       # 0.0, 0.1, 0.2, ..., 1.0
ax.set_xticks(new_ticks)


相反,您需要分别更新 x-ticks 的位置和标签:

# positions of each tick, relative to the indices of the x-values
ax.set_xticks(np.interp(new_ticks, s.index, np.arange(s.size)))

# labels
ax.set_xticklabels(new_ticks)

在大多数情况下,这种行为实际上很有意义。对于条形图,x 标签通常是非数字的(例如,对应于类别的字符串),在这种情况下,无法使用 x 中的值来设置刻度位置。在不引入另一个参数来指定它们的位置的情况下,最合乎逻辑的选择是使用它们的索引。

【讨论】:

  • 谢谢,这很有帮助。
  • 我也面临同样的问题。 AutoDateLocator 这样的 Matplotlib 功能可以在这种情况下提供帮助吗?
  • hmmm... 默认行为已更改,可能在 matplotlib 中。我找不到这方面的 ant 文档:i.stack.imgur.com/qJqde.png
  • hmmm2....:这可能是 Pandas 1.2.0 中的错误/回归,将在 1.2.1 中修复:github.com/pandas-dev/pandas/issues/38865
猜你喜欢
  • 2015-02-13
  • 2020-05-29
  • 1970-01-01
  • 1970-01-01
  • 2013-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-12
相关资源
最近更新 更多