pandas 在 matplotlib 中的刻度线之间居中 x-tick 标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17158382/
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
Centering x-tick labels between tick marks in matplotlib
提问by Osmond Bishop
I want to have the x-tick date labels centered between the tick marks, instead of centered about the tick marks as shown in the photo below.
我想让 x-tick 日期标签在刻度线之间居中,而不是以刻度线为中心,如下图所示。
I have read the documentation but to no avail - does anyone know a way to do this?
我已阅读文档但无济于事 - 有没有人知道这样做的方法?


Here is everything that I've used for my x-axis tick formatting if it helps:
如果有帮助,以下是我用于 x 轴刻度格式的所有内容:
day_fmt = '%d'
myFmt = mdates.DateFormatter(day_fmt)
ax.xaxis.set_major_formatter(myFmt)
ax.xaxis.set_major_locator(matplotlib.dates.DayLocator(interval=1))
for tick in ax.xaxis.get_major_ticks():
tick.tick1line.set_markersize(0)
tick.tick2line.set_markersize(0)
tick.label1.set_horizontalalignment('center')
采纳答案by jedwards
One way to do it is to use the minor ticks. The idea is that you set the minor ticks so that they are located halfway between the major ticks, and you manually specify the labels.
一种方法是使用小刻度。这个想法是您设置次要刻度,使它们位于主要刻度之间的中间,然后手动指定标签。
For example:
例如:
import matplotlib.ticker as ticker
# a is an axes object, e.g. from figure.get_axes()
# Hide major tick labels
a.xaxis.set_major_formatter(ticker.NullFormatter())
# Customize minor tick labels
a.xaxis.set_minor_locator(ticker.FixedLocator([1.5,2.5,3.5,4.5,5.5]))
a.xaxis.set_minor_formatter(ticker.FixedFormatter(['1','2','3','4','5']))
The three lines:
三行:
- "Hide" the 1,2,3,4,... that you have on the major ticks
- Set minor ticks halfway between the major ticks (assuming your major ticks are at 1,2,3...)
- Manually specifies the labels for the minor ticks. Here, '1' would be between 1.0 and 2.0 on the graph.
- “隐藏”主要刻度上的 1,2,3,4,...
- 在主要刻度之间设置小刻度(假设您的主要刻度在 1,2,3...)
- 手动指定次要刻度的标签。此处,图表上的“1”将介于 1.0 和 2.0 之间。
This is just a simple example. You would probably want to streamline it a bit by populating the lists in a loop or something.
这只是一个简单的例子。您可能希望通过在循环中填充列表或其他方式来简化它。
You can also experiment with other locators or formatters.
您还可以尝试使用其他定位器或格式化程序。
Edit:Alternatively, as suggested in the comments:
编辑:或者,如评论中所建议:
# Hide major tick labels
a.set_xticklabels('')
# Customize minor tick labels
a.set_xticks([1.5,2.5,3.5,4.5,5.5], minor=True)
a.set_xticklabels(['1','2','3','4','5'], minor=True)
Example:
例子:
Before:
前:
After:
后:
回答by runDOSrun
Here's an alternative to using Locators and Formatters. It can be used for any spacings between labels:
这是使用定位器和格式化程序的替代方法。它可用于标签之间的任何间距:
# tick_limit: the last tick position without centering (16 in your example)
# offset: how many steps between each tick (1 in your example)
# myticklabels: string labels, optional (range(1,16) in your example)
# need to set limits so the following works:
ax.xaxis.set_ticks([0, tick_limit])
# offset all ticks between limits:
ax.xaxis.set(ticks=np.arange(offset/2., tick_limit, offset), ticklabels=myticklabels)
# turn off grid
ax.grid(False)
Since this modifies the major ticks, the grid might have to be adjusted - depending on the application. It's also possible to work around this by using ax.twinx()). This will result in moving the labels on the opposite side of a separate axis but will leave the original grid untouched and giving two grids, one for the original ticks and one for the offsets.
由于这会修改主要刻度,因此可能需要调整网格 - 取决于应用程序。也可以使用ax.twinx())来解决此问题。这将导致在单独轴的另一侧移动标签,但不会触及原始网格并提供两个网格,一个用于原始刻度,一个用于偏移。
Edit:
编辑:
Assuming evenly spaced integer ticks, this is probably the most simple way:
假设均匀间隔的整数刻度,这可能是最简单的方法:
ax.set_xticks([float(n)+0.5 for n in ax.get_xticks()])
回答by aslan
A simple alternative is using horizontal alignment and manipulating the labels by adding spaces, as in the MWE below.
一个简单的替代方法是使用水平对齐并通过添加空格来操纵标签,如下面的 MWE 所示。
#python v2.7
import numpy as np
import pylab as pl
from calendar import month_abbr
pl.close('all')
fig1 = pl.figure(1)
pl.ion()
x = np.arange(120)
y = np.cos(2*np.pi*x/10)
pl.subplot(211)
pl.plot(x,y,'r-')
pl.grid()
new_m=[]
for m in month_abbr: #'', 'Jan', 'Feb', ...
new_m.append(' %s'%m) #Add two spaces before the month name
new_m=np.delete(new_m,0) #remove first void element
pl.xticks(np.arange(0,121,10), new_m, horizontalalignment='left')
pl.axis([0,120,-1.1,1.1])
fig1name = './labels.png'
fig1.savefig(fig1name)
The resulting figure:
结果图:

