要設置圖例的漸變樣式,可以使用matplotlib.patches
模塊中的Polygon
類,并將其添加到legend_handles_labels
參數中。
以下是一個示例代碼:
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 3, 6, 10, 15]
fig, ax = plt.subplots()
line1, = ax.plot(x, y1, label='Line 1')
line2, = ax.plot(x, y2, label='Line 2')
# 創建一個漸變樣式的圖例
legend_handles = [line1, line2]
legend_labels = [handle.get_label() for handle in legend_handles]
gradient = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)], facecolor='b', edgecolor='none', transform=fig.transFigure)
legend_handles.append(gradient)
legend_labels.append('Gradient')
ax.legend(legend_handles, legend_labels)
plt.show()
在這個示例中,我們創建了兩條折線圖并添加了一個漸變樣式的圖例。我們使用Polygon
類創建了一個矩形,并將其添加到了legend_handles
和legend_labels
中。最后,我們調用ax.legend()
方法來顯示圖例。