访问 matplotlib 中的轴标签字符串

Accessing axes label strings in matplotlib

我正在尝试在 matplotlib 中访问我的绘图的轴标签字符串,以便我可以创建一组新的它们。但是,每当我尝试使用 axes.get_xticklabels() 获取它们时,我只会在 return 中得到一个空字符串。我读到标签仅在调用 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.

当我显示() 绘图或保存绘图时,标签正常显示。但是上面的代码只打印空字符串。我也试过在循环后访问标签,但还是不行。

最奇怪的部分是,如果我删除循环部分并输入 i = 0,那么如果我将它逐行粘贴到 python 交互式终端中,它就会起作用,但如果我 运行 脚本...这部分令人困惑但并不重要。

我的代码有什么问题?我还需要为此做些什么吗?

这是我上一个问题的后续问题,没有引起太大关注。希望这更平易近人。

查看 plt.draw()documentation,您可以看到它实际上只是调用了 gcf.canvas.draw_idle(),它 "schedules a rendering the next time the GUI window is going to re-paint the screen". If we look at the source for gcf.canvas.draw_idle 你可以看到它只是在特定条件下调用 gcf.canvas.draw

相反,如果您使用 fig.canvas.draw(),您应该得到您要查找的内容,因为这将强制绘制图形。事实上,如果您查看 documentation,您会看到此函数渲染图形并“遍历 [s] 艺术家树,即使未生成输出也是如此,因为这会触发延迟工作(如计算限制自动-限制和刻度值)"

因此下面的代码应该可以满足您的需求。

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = plt.axes([0.1, 0.1, 0.8, 0.8])
ax.plot(np.random.random(100), '.')

fig.canvas.draw() # <---- This is the line you need

print(ax.get_xticklabels())
# [Text(-20.0, 0, '-20'), Text(0.0, 0, '0'), Text(20.0, 0, '20'), Text(40.0, 0, '40'), Text(60.0, 0, '60'), Text(80.0, 0, '80'), Text(100.0, 0, '100'), Text(120.0, 0, '120')]

作为结束语,文档还指出,在大多数情况下,gcf.canvas.draw_idlegcf.canvas.draw 更可取,以减少不必要地渲染图形所花费的时间。