首页 > 解决方案 > 自定义嵌套圆环图 - Python

问题描述

我相信我已经解决了这个问题的 90%。从附图中可以看出,我正在尝试基于两个组(rem 和 deep)创建一个嵌套的圆环图,这些值已被绘制以显示用户实现的比例(相对于 100%)。我想以“苹果健康环样式”显示它,为了使其有效,我想使用两种不同的颜色突出显示两种“类型”(rem 和 deep)。在图像中,您可以看到 DF、用于生成现有视图和输出的代码。总而言之,我想;

  1. 为“rem”分配一种颜色,为“deep”分配不同的颜色
  2. 删除轴标签和刻度线
  3. 理想情况下(尽管我可能可以这样做),更好地格式化标签(以某种方式)。
  4. 输出到黑色背景的图像文件
import re
# create donut plots
my_dpi=150
plt.figure(figsize=(1500/my_dpi, 900/my_dpi), dpi=my_dpi)
startingRadius = 0.7 + (0.3* (len(Ian_MitchellRD)-1))

for index, row in Ian_MitchellRD.iterrows():
    scenario = row["index"]
    percentage = row["Ian Mitchell"]
    textLabel = scenario + ': ' + percentage+ '%'
    print(startingRadius)
    percentage = int(re.search(r'\d+', percentage).group())
    remainingPie = 100 - percentage

    donut_sizes = [remainingPie, percentage]
    #colors = ['#FDFEFE','#AED6F1','#5cdb6f','#AED6F1']
    plt.title('Proportion of Recommended Sleep Type being Achieved')
    plt.text(0.05, startingRadius - 0.20, textLabel, horizontalalignment='left', verticalalignment='center', color='black')
    plt.pie(donut_sizes, radius=startingRadius, startangle=90, colors=colors, frame=True,
            wedgeprops={"edgecolor": "white", 'linewidth': 2}, )
    startingRadius-=0.3

# equal ensures pie chart is drawn as a circle (equal aspect ratio)
plt.axis('equal')

# create circle and place onto pie chart
circle = plt.Circle(xy=(0, 0), radius=0.35, facecolor='white')
plt.gca().add_artist(circle)
plt.show()

查看当前代码生成的图像:

更新:

我根据建议修改了代码以查看建议的示例,现在是代码;

import matplotlib.lines as mlines
fig, ax = plt.subplots()
ax.axis('equal')
width = 0.25
fig.patch.set_facecolor('black')
fig.set_size_inches(10,10)

data_1 = Ian_MitchellRD.iloc[0]['Ian Mitchell']
data_2 = Ian_MitchellRD.iloc[1]['Ian Mitchell']

remainingPie_1 = 100 - data_1
remainingPie_2 = 100 - data_2

donut_sizes_1 = [remainingPie_1, data_1]
donut_sizes_2 = [remainingPie_2, data_2]

pie, _ = ax.pie(donut_sizes_1, radius=1, colors=['black','lightgreen'],startangle=90)
plt.setp( pie, width=width, edgecolor='black')

pie2, _ = ax.pie(donut_sizes_2, radius=1-width,startangle=90, colors=['black','pink'])
plt.setp( pie2, width=width, edgecolor='black')
plt.title("Ian Mitchell - Average % of REM + Deep Sleep vs Recommended", fontfamily='Consolas', size=16, color='white')

#setting up the legend

greenbar= mlines.Line2D([], [], color='lightgreen', marker='s', linestyle='None',
                          markersize=10, label='REM Sleep')
pinkbar = mlines.Line2D([], [], color='pink', marker='s', linestyle='None',
                          markersize=10, label='Deep Sleep')

plt.legend(handles=[greenbar, pinkbar],prop={'size': 12}, loc='lower right')
plt.show()

生成以下内容;

我非常感谢直接在图表的相关部分添加标签的指导 - 即绿色图表的标签约为 94%,粉红色部分的标签约为 55%。

谢谢,

新版本

标签: pythonpandasmatplotlibdata-visualization

解决方案


推荐阅读