Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在matplotlib中的记号标记之间居中x记号标签_Python_Matplotlib_Pandas - Fatal编程技术网

Python 在matplotlib中的记号标记之间居中x记号标签

Python 在matplotlib中的记号标记之间居中x记号标签,python,matplotlib,pandas,Python,Matplotlib,Pandas,我想让x-tick日期标签在刻度线之间居中,而不是如下图所示以刻度线为中心 我已经阅读了文档,但没有结果-有人知道这样做的方法吗 以下是我在x轴勾号格式中使用的所有内容(如果有帮助): day_fmt = '%d' myFmt = mdates.DateFormatter(day_fmt) ax.xaxis.set_major_formatter(myFmt) ax.xaxis.set_major_locator(matplotlib.dates.DayLocator(inter

我想让x-tick日期标签在刻度线之间居中,而不是如下图所示以刻度线为中心

我已经阅读了文档,但没有结果-有人知道这样做的方法吗

以下是我在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')

一种方法是使用小刻度。这样做的目的是设置次要记号,使其位于主要记号之间的中间位置,然后手动指定标签

例如:

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']))
三行:

  • “隐藏”1,2,3,4,。。。你在主刻度上的刻度
  • 在主刻度的中间设置小刻度(假设主刻度为1,2,3…)
  • 手动指定次要记号的标签。这里,“1”在图上应该在1.0和2.0之间
这只是一个简单的例子。您可能希望通过在循环或其他方式中填充列表来简化它

你也可以尝试其他的方法

编辑:或者,按照评论中的建议:

# 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)

例子: 之前:

之后:
这里有一个替代使用定位器和格式化程序的方法。它可用于标签之间的任何间距:

# 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()])

一个简单的替代方法是使用水平对齐,并通过添加空间来操纵标签,如下面的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)
由此得出的数字:


谢谢,我来试试这个。有没有办法将已经存在的x轴记号标签作为列表返回,我可以使用它?我已经浏览了文档,但运气不太好。
a.xaxis.get_majorticklabels()
返回一个iterable,您可以使用类似于a.xaxis.get_majorticklabels()中tl的
来循环它。但请注意,此列表中的元素并非您所期望的字符串,而是
matplotlib.text.text
对象。要获取字符串,您需要类似以下内容:
[tl.get_text()for tl in a.xaxis.get_majorticklabels()]
。不过,值得注意的是,这些值在实际绘制绘图之前是无法确定的。因此,它们并不是获取标签的好方法。直接从数据中获取值会更好。我的x轴由半小时数据组成,因此我没有创建位置,而是添加了以下内容:
ax.xaxis.set_minor_formatter(myFmt)
ax.xaxis.set_minor_locator(matplotlib.dates.HourLocator(interval=12))
并将我的主格式化程序更改为您所做的那样,
ax.xaxis.set_major_格式化程序(ticker.NullFormatter())
但由于某些原因,它没有隐藏主刻度标签,还有什么我可能缺少的吗?您可以通过使用
a.set_xticks
a.set_xticklabels
来实现这一点更简单。两者都采用一个名为minor的可选布尔参数,使其影响次要刻度,例如
a.set_xticklabels(“”);x、 设置_xticks([1.5,2.5,3.5,4.5,5.5],次要=真);a、 设置标签(['1'、'2'、'3'、'4'、'5'],次要值=True)