python - 在 matplotlib 中操作 x 轴刻度标签

标签 python matplotlib pandas bar-chart

我注意到当我的条形图中有 5 个或更少的数据条时,x 轴会自动添加额外的刻度: enter image description here 我想要的是这样的:

enter image description here

有什么方法可以强制 matplotlib 为第一张图的每个条柱生成一个刻度标签吗?

最佳答案

bar 方法接受一个参数align。将此参数设置为 align='center'align 将条形对齐到我们给它的 x 值的中心,而不是对齐到条形的左侧(这是默认设置)。

然后使用xticks 方法指定 x 轴上有多少个刻度以及放置它们的位置。

import matplotlib.pyplot as plot

x = range(1, 7)
y = (0, 300, 300, 290, 320, 315)
plot.bar(x, y, width=0.7, align="center")

ind = range(2, 7)    # the x locations for the groups
plot.xticks(ind, x)

plot.axhline(305, linewidth=3, color='r')

plot.show()

文档位于 http://matplotlib.org/api/pyplot_api.html

关于python - 在 matplotlib 中操作 x 轴刻度标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15777945/

相关文章:

python - 在matplotlib直方图的y轴上调用函数

python - 具有线条和面积样式的 Matplotlib 图例

python - Pycharm Jupyter 交互式 Matplotlib

pandas - TypeError : Series. name must be a hashable type

python - 装饰器——试图理解这个简单的例子

python - 使用 BS4 获取属性名称而不是值

Python:如果安装了同一个包的多个 egg 版本,我该如何具体导入我需要的版本?

python - 自动编译父模板

python - 将复杂的 str 更改为 pandas Dataframe 中的 float

python - 使用 groupby 和 loc 设置新的数据框