Matplotlib中怎么自定義圖例填充漸變顏色

小億
169
2024-05-11 17:17:51

要在Matplotlib中自定義圖例填充漸變顏色,可以使用Legend對(duì)象的set_facecolor方法來(lái)設(shè)置圖例的填充顏色為漸變色。

首先,需要導(dǎo)入必要的庫(kù):

import matplotlib.pyplot as plt
from matplotlib.legend import Legend
from matplotlib.colors import LinearSegmentedColormap

然后,創(chuàng)建一個(gè)自定義的漸變色映射:

cmap = LinearSegmentedColormap.from_list('my_cmap', ['blue', 'green', 'red'])

接下來(lái),創(chuàng)建一個(gè)圖例并設(shè)置其填充顏色為漸變色:

fig, ax = plt.subplots()
line1, = ax.plot([1, 2, 3], label='Line 1')
line2, = ax.plot([3, 2, 1], label='Line 2')
legend = ax.legend(handles=[line1, line2], labels=['Line 1', 'Line 2'])

legend.get_frame().set_facecolor(cmap(0.5))  # 設(shè)置圖例填充顏色為漸變色的中間值

通過(guò)這種方法,可以自定義Matplotlib圖例的填充顏色為漸變色。

0