簡體   English   中英

在 matplotlib 中訪問軸標簽字符串

[英]Accessing axes label strings in matplotlib

我試圖在 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.

當我顯示()繪圖或保存它時,標簽會正常顯示。 但是上面的代碼只打印空字符串。 我也嘗試在循環后訪問標簽,但它仍然不起作用。

最奇怪的部分是,如果我刪除循環部分並放入 i = 0,那么如果我將其逐行粘貼到 python 交互式終端中,它就可以工作,但如果我運行腳本則不行……這部分令人困惑,但是沒那么重要。

我的代碼有什么問題? 我還需要為此做些什么嗎?

這是我上一個問題的后續問題,該問題沒有得到太多關注。 希望這更平易近人。

這似乎可以滿足您的需求:

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