我試圖在 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 互動式終端中,則它會起作用,但如果我運行腳本則不會......這部分令人困惑,但是沒那么重要。
我的代碼有什么問題?我還需要為此做些什么嗎?
這是我上一個問題的后續問題,該問題沒有得到太多關注。希望這更平易近人。
uj5u.com熱心網友回復:
這似乎可以滿足您的需求:
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')]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/337708.html
標籤:Python 细绳 matplotlib 阴谋 轴标签
