一个楔块上具有较小宽度的Python matplotlib圆环图

2024-09-30 10:33:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图重新创建一个甜甜圈图表,其中最后一个楔子比其他楔子薄,如下所示:

enter image description here

但是我找不到一种方法使最后一个楔子的宽度变小。所以我试着让最后一个楔子与背景颜色相同,并在顶部画一个灰色的圆环。但是我不能在楔子下面画圆环,也不能让上面的层在正确的地方是透明的

有没有办法使单个楔子透明,或者解决我的问题

以下是我目前的代码:

import matplotlib.pyplot as plt
donut = [150,10,20,20,30,40]
total = sum(donut)
grey_circle = plt.Circle((0,0),0.965,color='#CCCCCC', lw=1, fill=False)
centre_circle = plt.Circle((0,0),0.93,fc='white')
fig, ax = plt.subplots(figsize=(2, 2), subplot_kw=dict(aspect="equal"))
colors = ['#F8F5EB','#50E3C2','#FF9100','#002776','#C94096','#0071CD' ]
wedges, texts = ax.pie(donut, colors=colors, wedgeprops=dict(width=0.1), startangle=90)
fig.gca().add_artist(grey_circle)
fig.gca().add_artist(centre_circle)
fig.set_facecolor('#F8F5EB')
fig = plt.gcf()
plt.savefig('cirle.png',facecolor=fig.get_facecolor(), edgecolor='none', dpi=300)

plt.show() 

我的结果是:

enter image description here


Tags: figpltaxdictgreycolorscirclecentre
1条回答
网友
1楼 · 发布于 2024-09-30 10:33:56

最简单的方法是绘制两次图表,一次用于厚楔,一次用于薄楔。不绘制的楔块颜色设置为“无”。设置显式半径将为薄楔创建正确的尺寸

使用这种方法,不需要圆圈来隐藏东西。您仍然可以添加一个圆以在中心获得不同的颜色。只需添加zorder=0以确保圆位于饼图后面

一些代码用于说明这些概念:

import matplotlib.pyplot as plt

donut = [150, 10, 20, 20, 30, 40]

thin_indices = [0]  # indices of all wedges that should be thin
colors = ['#CCCCCC', '#50E3C2', '#FF9100', '#002776', '#C94096', '#0071CD']
colors_thin = [c if i in thin_indices else 'none' for i, c in enumerate(colors)]
colors_thick = [c if i not in thin_indices else 'none' for i, c in enumerate(colors)]
radius = 1
thick_width = 0.1
thin_width = 0.05
radius_thin = radius - 0.5 * (thick_width - thin_width)

fig, ax = plt.subplots(figsize=(2, 2), subplot_kw=dict(aspect="equal"))
ax.pie(donut, radius=radius, colors=colors_thick, wedgeprops=dict(width=thick_width), startangle=90)
ax.pie(donut, radius=radius_thin, colors=colors_thin, wedgeprops=dict(width=thin_width), startangle=90)
centre_circle = plt.Circle((0, 0), radius - thick_width/2, fc='white', zorder=0)
ax.add_artist(centre_circle)

fig.set_facecolor('#F8F5EB')
plt.savefig('cirle.png', facecolor=fig.get_facecolor(), edgecolor='none', dpi=300)

plt.show()

resulting donut plot

相关问题 更多 >

    热门问题