访问matplotlib中的轴标签字符串

2024-10-02 04:35:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在matplotlib中访问绘图的轴标签字符串,以便创建一组新的字符串。但是,每当我尝试使用axis.getxticklabels()获取它们时,我只会得到一个空字符串作为回报。我了解到标签只在调用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交互终端中,它就会工作,但如果我运行脚本,它就不会工作。。。这一部分令人困惑,但没有那么重要

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

这是我上一个问题的后续问题,没有得到太多的关注。希望这更容易接近


Tags: theto字符串in绘图formatplotlibnp
1条回答
网友
1楼 · 发布于 2024-10-02 04:35:30

查看plt.draw()documentation,您可以看到它实际上只是调用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

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

因此,下面的代码应该满足您的要求

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更适合减少不必要的图形渲染时间

相关问题 更多 >

    热门问题