我需要將圖例創建為單獨的圖形,更重要的是可以將其保存在新檔案中的單獨實體。我的情節由線條和填充的線段組成。
問題是fill_between元素,我無法將其添加到外部圖形/圖例中。
我意識到,這是一種不同型別的物件,它是一個PolyCollection,而線圖是Line2D元素。
我如何處理PolyCollection以便我可以在外部圖例中使用它?
資訊:matplotlib 版本 3.3.2
import matplotlib.pyplot as plt
import numpy as np
# Dummy data
x = np.linspace(1, 100, 1000)
y = np.log(x)
y1 = np.sin(x)
# Create regular plot and plot everything
fig = plt.figure('Line plot')
ax = fig.add_subplot(111)
line1, = ax.plot(x, y)
line2, = ax.plot(x, y1)
fill = ax.fill_between(x, y, y1)
ax.legend([line1, line2, fill],['Log','Sin','Area'])
ax.plot()
# create new plot only for legend
legendFig = plt.figure('Legend plot')
legendFig.legend([line1, line2],['Log','Sin']) <----- This works
# legendFig.legend([line1, line2, fill],['Log','Sin', 'Area']) <----- This does not work
uj5u.com熱心網友回復:
你忘了提到這里不起作用的意思。顯然,您會收到一條錯誤訊息:RuntimeError: Can not put single artist in more than one figure.
Matplotlib 不允許放置在一個圖形中的元素在另一個圖形中重復使用。line沒有給出錯誤只是一個幸運的巧合。
要在另一個圖形中使用元素,您可以創建一個新元素,并從原始元素復制樣式:
from matplotlib.lines import Line2D
from matplotlib.collections import PolyCollection
legendFig = plt.figure('Legend plot')
handle_line1 = Line2D([], [])
handle_line1.update_from(line1)
handle_line2 = Line2D([], [])
handle_line2.update_from(line2)
handle_fill = PolyCollection([])
handle_fill.update_from(fill)
legendFig.legend([handle_line1, handle_line2, handle_fill], ['Log', 'Sin', 'Area'])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/342639.html
標籤:Python matplotlib
上一篇:如何在圖表上設定xticks
下一篇:如何用100萬點散點圖
