我想让x-tick date标签在刻度线之间居中,而不是在刻度线周围居中,如下图所示。
我已经阅读了文档,但无济于事--有人知道如何做到这一点吗?
以下是我在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')
发布于 2016-07-08 21:03:41
这里有一种替代使用定位器和Formatters的方法。它可以用于标签之间的任何间距:
# 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)
由于这会修改主要的刻度,因此网格可能需要根据应用程序进行调整。也可以通过使用ax.twinx()
来解决这个问题)。这将导致在单独的轴的另一侧上移动标签,但将保持原始网格不变,并提供两个网格,一个用于原始记号,另一个用于偏移。
编辑:
假设整数刻度间隔均匀,这可能是最简单的方法:
ax.set_xticks([float(n)+0.5 for n in ax.get_xticks()])
发布于 2018-10-26 20:22:39
一种简单的替代方法是使用水平对齐并通过添加空格来操作标签,如下面的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)
由此得到的图:
https://stackoverflow.com/questions/17158382
复制相似问题