Python 在 matplotlib 中操作 x 轴刻度标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15777945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Manipulating x axis tick labels in matplotlib
提问by Osmond Bishop
I have noticed that when I have 5 or less bars of data in my bar graph the x-axis automatically adds in extra ticks:
What I want is something like this:
我注意到当我的条形图中有 5 个或更少的数据条时,x 轴会自动添加额外的刻度:
我想要的是这样的:


Is there any way I can force matplotlib to generate just one tick label per bar for the first graph?
有什么方法可以强制 matplotlib 为第一个图形的每个条形生成一个刻度标签?
采纳答案by twasbrillig
The barmethod takes a parameter align. Set this parameter as align='center'. alignaligns the bars on the center of the x values we give it, instead of aligning on the left side of the bar (which is the default).
该bar方法接受一个参数align。将此参数设置为align='center'。align将条形对齐我们给它的 x 值的中心,而不是在条形的左侧对齐(这是默认值)。
Then use the xticksmethod to specify how many ticks on the x-axis and where to place them.
然后使用该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()
Docs are at http://matplotlib.org/api/pyplot_api.html

