使用颜色渐变的 Matplotlib 饼图楔形

Matplotlib pie chart wedges using color gradient

我正在尝试创建一个饼图,其中每个楔形具有不同的颜色渐变(例如,黄绿色),而不是单一颜色(例如,绿色)。进一步解释一下,渐变应该沿着半径而不是圆周设置。

尝试了很多选项并在网上做了一些研究,但找不到直接的解决方案。

有没有我应该采用的库或方法来实现这一点?

提前致谢。

您可以创建具有所需渐变的图像,然后通过每个楔形定位和剪裁它。 LinearSegmentedColormap.from_list() 在给定颜色之间进行插值。

这是一个例子:

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np

fig, ax = plt.subplots()

sizes = np.random.uniform(10, 20, 4)
color_combos = [('yellow', 'green'), ('red', 'navy'), ('yellow', 'crimson'), ('lime', 'red')]
wedges, texts = ax.pie(sizes, labels=['alpha', 'beta', 'gamma', 'delta'])
xlim = ax.get_xlim()
ylim = ax.get_ylim()
for wedge, color_combo in zip(wedges, color_combos):
    wedge.set_facecolor('none')
    wedge.set_edgecolor('black')
    print(wedge.theta1, wedge.theta2)
    bbox = wedge.get_path().get_extents()
    x0, x1, y0, y1 = bbox.xmin, bbox.xmax, bbox.ymin, bbox.ymax
    x = np.linspace(x0, x1, 256)[np.newaxis, :]
    y = np.linspace(y0, y1, 256)[:, np.newaxis]
    # fill = np.sqrt(x ** 2 + y ** 2) # for a gradient along the radius, needs vmin=0, vmax=1
    fill = np.degrees(np.pi - np.arctan2(y, -x))
    gradient = ax.imshow(fill, extent=[x0, x1, y0, y1], aspect='auto', origin='lower',
                         cmap=LinearSegmentedColormap.from_list('', color_combo),
                         vmin=wedge.theta1, vmax=wedge.theta2)
    gradient.set_clip_path(wedge)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
ax.set_aspect('equal')
plt.show()

左边是沿角度的渐变示例,右边是沿半径的渐变示例。