」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何防止Matplotlib中圖例被截斷並保持資料可見性?

如何防止Matplotlib中圖例被截斷並保持資料可見性?

發佈於2024-11-02
瀏覽:408

How to Prevent Cut-off Legend in Matplotlib and Maintain Data Visibility?

透過調整圖形框大小來解決Matplotlib 中的截斷圖例問題

在Matplotlib 中,將圖例移到繪圖軸之外通常會導致其被圖形框截斷。雖然縮小軸被建議作為一種解決方案,但它會降低資料可見性,特別是在呈現具有大量圖例條目的複雜繪圖時。

正如Benjamin Root 在Matplotlib 郵件列表上的回復中所強調的,更有效的方法包括:修改savefig 呼叫以將圖例合併為額外藝術家:

fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')

此方法,類似使用tight_layout,使savefig在計算圖形框大小時考慮圖例。

以下增強的程式碼範例示範了解決方案:

import matplotlib.pyplot as plt
import numpy as np

plt.gcf().clear()
x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
handles, labels = ax.get_legend_handles_labels()
lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1))
text = ax.text(-0.2,1.05, "Aribitrary text", transform=ax.transAxes)
ax.set_title("Trigonometry")
ax.grid('on')
fig.savefig('samplefigure', bbox_extra_artists=(lgd,text), bbox_inches='tight')

現在可以動態調整圖形框大小以適應圖例,防止其被截斷,同時保持資料可見性。

版本聲明 本文轉載於:1729223656如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3