【问题标题】:Accessing axes label strings in matplotlib在 matplotlib 中访问轴标签字符串
【发布时间】: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


【解决方案1】:

查看documentation for plt.draw(),你可以看到它实际上只是调用了gcf.canvas.draw_idle(),它 “schedules a rendering the next time the GUI window is going to re-paint the screen”。如果我们查看source for gcf.canvas.draw_idle,您会发现它只是在某些条件下调用gcf.canvas.draw

相反,如果你使用fig.canvas.draw(),你应该得到你正在寻找的东西,因为这将强制绘制图形。事实上,如果你看一下documentation,你会看到这个函数会渲染图形并且“walk[s] the artist tree即使没有输出是因为这会触发延迟工作(比如计算限制自动限制和刻度值)”

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

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 更可取,以减少不必要地渲染图形所花费的时间。

【讨论】:

  • 这似乎可行,谢谢!我仍然不知道为什么它有时会更早地起作用,但这并不重要。
  • @syzygy350,我更新了答案,希望这有助于解释原因。不确定draw_idle 可以满足您的需求的确切条件,但如上所述,它plt.draw 调用gcf.canvas.draw_idle,它在某些条件下调用gcf.canvas.draw
猜你喜欢
  • 2011-11-25
  • 1970-01-01
  • 1970-01-01
  • 2020-07-02
  • 1970-01-01
  • 2020-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多