我正在嘗試將 matplotlibText實體自動移動到一些注釋之上,這些注釋沒有被plt.tight_layout或考慮在內constrained_layout。
但是,我似乎無法在Text.set_position之后使用和重繪來更新標題位置(無論是在使用例如fig.canvas.draw()每次更新時還是在呼叫時title_text_instance.draw(renderer=fig.canvas.get_renderer()))。
文本本身似乎更新得很好,另一個注釋也是如此,這很奇怪,因為標題和注釋都是Text物件。
為什么下面代碼中的標題位置沒有更新?
影片說明;標題文本和注釋位置按預期更新,但其位置保持固定:

代碼:
#!/usr/bin/env/python3
import matplotlib.pyplot as plt
import matplotlib as mpl
N_FRAMES: int = 10
# Setting up the example.
mpl.use("TkAgg")
fig, ax = plt.subplots(figsize=(2, 1), dpi=300)
ax.plot(range(10), range(10))
t = ax.set_title("Example title", fontsize=6, alpha=.8, clip_on=False)
atext1 = '\n'.join(['Overlapping extra-axis annotation',
'above which I want to move the title',
'undetected by tight_layout or constrained_layout'])
atext2 = 'this annotation moves just fine...'
a1 = ax.annotate(atext1, xycoords='axes fraction', xy=(.25, 1),
rotation=10, clip_on=False, fontsize=3, color='r', alpha=.6)
a2 = ax.annotate(atext2, xycoords='axes fraction', xy=(.5, .5),
clip_on=False, fontsize=4, color='g')
fig.canvas.draw()
plt.tight_layout()
# ^^ Leaving out plt.tight_layout doesn't
# make a difference w.r.t position updates
for yoffset in range(N_FRAMES):
new_position = (t.get_position()[0], t.get_position()[1] - .5 (yoffset / 2))
newpostext = '(' ', '.join(f'{pos:.2f}' for pos in new_position) ')'
# Changing positions
print(f'Set new position to', newpostext)
t.set_position(new_position) # Doesn't work
a2.set_position(new_position) # Works fine
t.set_text(f"Supposedly repositioned title position: \n (x, y) = {newpostext}")
plt.pause(.5)
plt.get_current_fig_manager().window.resizable(False, False)
plt.show(block=False)
plt.close(fig)
uj5u.com熱心網友回復:
除非您明確指定 title 的 y 位置,否則_autotitlepostitle有一個內部屬性設定為True。因此,為了能夠手動設定標題位置,您需要y在設定標題時提供一個值,例如默認值1:
t = ax.set_title("Example title", fontsize=6, alpha=.8, clip_on=False, y=1)
(最低 matplotlib 版本 3.3.0,參見PR #17127)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/352387.html
標籤:Python matplotlib 阴谋 格式化 重叠
下一篇:多元線性回歸模型的等值線圖
