【发布时间】:2021-10-25 22:42:00
【问题描述】:
我正在尝试在 matplotlib 中访问我的绘图的轴标签字符串,以便我可以创建一组新的字符串。但是,每当我尝试使用 axes.get_xticklabels() 获取它们时,我只会得到一个空字符串作为回报。我读到只有在调用 draw() 方法后才会填充标签,但调用 pyplot.draw() 在这里什么都不做。
ax=0
for i in yvar:
hist00, ext00, asp00 = histogram(np.log10(df[spn[xvar]]), np.log10(df[spn[i]]), 100, False)
axes[ax].imshow(hist00, norm = matplotlib.colors.LogNorm(), extent = ext00, aspect = asp00)
# This first part of the code just has to do with my custom plot, so I don't think it should affect the problem.
plt.draw() # Calling this to attempt to populate the labels.
for item in axes[ax].get_xticklabels():
print(item.get_text()) # Printing out each label as a test
ax +=1 # The axes thing is for my multi-plot figure.
当我 show() 绘图或保存它时,标签会正常显示。但是上面的代码只打印空字符串。我也尝试在循环之后访问标签,但它仍然不起作用。
最奇怪的部分是,如果我删除循环部分并放入 i = 0,那么如果我将它逐行粘贴到 python 交互式终端中,它会起作用,但如果我运行脚本则不会......这部分令人困惑,但并不那么重要。
我的代码有什么问题?我还需要为此做些什么吗?
这是我之前的问题的后续问题,没有引起太大的关注。希望这更平易近人。
【问题讨论】:
-
matplotlib online 在最后一刻创建刻度标签,就在绘图之前。只有当最后一个元素被添加到图中时,才能知道确切的范围并且可以计算位置。
标签: python string matplotlib plot axis-labels