我想在绘图之前修改我的xticklabels,但是plt.draw()似乎没有更新值。如何在使用plt.show()?
进行绘图之前更新这些值import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
num_bins = 50
x = 100 + 15 * np.random.randn(10000)
# the histogram of the data
n, bins, patches = plt.hist(x, num_bins, facecolor='green', alpha=0.5)
ax.set_ylabel('Number')
ax.set_xlabel('Distance')
ax.set_title('Distance vs. Number')
# Draw the canvas, otherwise the labels won't be positioned and have values
ax.get_figure().canvas.draw()
fig.canvas.draw()
plt.draw()
# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15)
for xl in ax.get_xticklabels(): print xl # Values not set
plt.show()
for xl in ax.get_xticklabels(): print xl # Values set
答案 0 :(得分:1)
您不需要plt.draw()
来达到预期的结果
事实上,标签实际上是在你绘制它们时更新的 - 所以你的图显示了意图。但是,在创建绘图之后,从轴读取正确的标签不起作用。
考虑这个例子(添加一行只分配两个xticks和标签):
plt.xticks([20,135],['one', 'two'])
for xl in ax.get_xticklabels(): print xl # Values not set
plt.show()
for xl in ax.get_xticklabels(): print xl # Values set
您看到的输出是: