温馨提示×

Matplotlib中怎么设置图例的渐变样式

小亿
85
2024-05-11 19:35:55
栏目: 编程语言

要设置图例的渐变样式,可以使用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_handleslegend_labels中。最后,我们调用ax.legend()方法来显示图例。

0