简体   繁体   English

在 matplotlib 中访问轴标签字符串

[英]Accessing axes label strings in matplotlib

I am trying to access the axis label strings for my plot in matplotlib so that I can then create a new set of them.我试图在 matplotlib 中访问我的绘图的轴标签字符串,以便我可以创建一组新的它们。 However, whenever I try to get them with axes.get_xticklabels(), I only get an empty string in return.但是,每当我尝试使用axes.get_xticklabels() 获取它们时,我只会得到一个空字符串作为回报。 I read that the labels are only populated after a draw() method is called, but calling pyplot.draw() does nothing here.我读到标签仅在调用 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.

The labels show up normally when I show() the plot, or when I save it.当我显示()绘图或保存它时,标签会正常显示。 But the code above only prints empty strings.但是上面的代码只打印空字符串。 I also tried to access the labels after the loop, but it still didn't work.我也尝试在循环后访问标签,但它仍然不起作用。

The weirdest part of this is that if I remove the looping part and put in i = 0, then it works if I paste it into python interactive terminal line by line, but not if I run the script... This part is confusing but not as important.最奇怪的部分是,如果我删除循环部分并放入 i = 0,那么如果我将其逐行粘贴到 python 交互式终端中,它就可以工作,但如果我运行脚本则不行……这部分令人困惑,但是没那么重要。

What is the problem with my code?我的代码有什么问题? Is there something else I need to do for this?我还需要为此做些什么吗?

This is a follow-on from my previous question, which didn't get much traction.这是我上一个问题的后续问题,该问题没有得到太多关注。 Hopefully this is more approachable.希望这更平易近人。

This seems to do what you need:这似乎可以满足您的需求:

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')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM