在Matplotlib中显示图之前获取空的刻度标签 [英] Getting empty tick labels before showing a plot in Matplotlib

查看:162
本文介绍了在Matplotlib中显示图之前获取空的刻度标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题与此处报道的问题相似.我不明白为什么刻度标签文本为空字符串:

I'm experiencing a similar issue to the one reported here. I don't understand why the tick label text is an empty string:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,2*np.pi,100)
y = np.sin(x)**2

fig, ax = plt.subplots()
ax.plot(x,y)

labels = ax.get_xticklabels()
for label in labels:
    print(label)

plt.show()

输出:

Text(0,0,'')
Text(0,0,'')
Text(0,0,'')
Text(0,0,'')
Text(0,0,'')
Text(0,0,'')
Text(0,0,'')
Text(0,0,'')

我用ax.xaxis.get_ticklabels()得到了相同的结果,但是绘制的图形在保存或显示时在x轴上显示了八个标记的刻度.但是,如果我在显示图后要求 后加标签,则labels列表将正确填充.当然,现在要更改它们,现在做任何事情都为时已晚.

I get the same result with ax.xaxis.get_ticklabels() but the plotted graph shows eight labelled ticks on the x-axis when saved or shown. However, if I ask for the labels after I show the plot, then the labels list is properly populated. Of course, it's a bit late to do anything about changing them then.

fig, ax = plt.subplots()
ax.plot(x,y)
plt.show()

labels = ax.get_xticklabels()
for label in labels:
    print(label)

输出:

Text(0,0,'0')
Text(1,0,'1')
Text(2,0,'2')
Text(3,0,'3')
Text(4,0,'4')
Text(5,0,'5')
Text(6,0,'6')
Text(7,0,'7')

为什么会发生这种情况(Mac OS X Yosemite,Matplotlib 1.5.1),并且在显示或保存绘图之前,如何在之前获得标签?

Why does this happen (Mac OS X Yosemite, Matplotlib 1.5.1) and how can I get my labels before I show or save my plot?

推荐答案

您已正确识别问题:在调用plt.show()之前,未明确设置任何内容.这是因为matplotlib除非有必要,否则避免了刻度线的静态定位,因为您可能想与之交互:例如,如果您可以ax.set_xlim().

You've correctly identified the problem: before you call plt.show() nothing is explicitly set. This is because matplotlib avoids static positioning of the ticks unless it has to, because you're likely to want to interact with it: if you can ax.set_xlim() for example.

在您的情况下,可以使用fig.canvas.draw()绘制图形画布以触发刻度线定位,以便检索其值.

In your case, you can draw the figure canvas with fig.canvas.draw() to trigger tick positioning, so you can retrieve their value.

或者,您可以显式设置xticks,依次将轴设置为FixedFormatterFixedLocator并获得相同的结果.

Alternatively, you can explicity set the xticks that will in turn set the the axis to FixedFormatter and FixedLocator and achieve the same result.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,2*np.pi,100)
y = np.sin(x)**2

fig, ax = plt.subplots()

ax.plot(x,y)
ax.set_xlim(0,6)

# Must draw the canvas to position the ticks
fig.canvas.draw()
# Or Alternatively
#ax.set_xticklabels(ax.get_xticks())

labels = ax.get_xticklabels()
for label in labels:
    print(label.get_text())

plt.show()

Out:
0
1
2
3
4
5
6

这篇关于在Matplotlib中显示图之前获取空的刻度标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆