将百分比标签添加到三级甜甜圈图 [英] add percent labels to three-level donut chart

查看:61
本文介绍了将百分比标签添加到三级甜甜圈图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的三层甜甜圈图中的每个标签和层添加百分比值.

以下代码适当地生成了三层甜甜圈图和图例.但是,它弄乱了百分比值的显示(请参阅此问题底部的输出图).

堆栈溢出或其他地方的当前解决方案仅适用于向饼图/甜甜圈图添加百分比值(例如:

有人可以指导我如何在每个甜甜圈圈中整齐地显示百分比值吗?

解决方案

总结我的评论,以下是我获得更好图形输出的代码,并且我相信您在寻找什么:

 将matplotlib.pyplot导入为plt将numpy导入为np#可以从pie中调用的示例函数(autopct = autopct)def autopct(pct):如果 pct >0.5:返回 f'{pct:.2f}%'别的:返回 '​​'无花果= plt.figure()fig.set_figheight(7)fig.set_figwidth(22)ax1 = fig.add_subplot(121)first_labels = ('邦乔维','超人','大流士皇家','Stargazer 1991 Viz','强制性Vis1','格特鲁德','特林贝尔','奥利奥','Iniwaka')first_sizes =(2000、300、200、100、100、150、40、30、700)second_sizes = (1000, 200, 200, 400, 500, 40, 1, 1, 1000)第三个尺寸 = (500, 300, 400, 500, 400, 100, 5, 2, 800)Flatui =(sns.diverging_palette(20,250,n = 8))更大 = plt.pie(first_sizes,颜色= flatui,startangle = 90,frame = True,半径=1,楔子道具= {'edgecolor':'k'},# autopct='%.2f%%',autopct=autopct,距离=1)较小 = plt.pie(第二个尺寸,颜色=扁平,半径= 0.9,startangle = 90,楔子道具= {'edgecolor':'k'},# autopct='%.2f%%',autopct=autopct,pctdistance=.9)最小的 = plt.pie(third_sizes,颜色= flatui,半径=0.8,起始角=90,楔子道具= {'edgecolor':'k'},#autopct ='%.2f %%',autopct=autopct,pctdistance = .8)center_circle = plt.Circle((0,0),0.7,color ='white',线宽= 0)plt.gca().add_artist(center_circle)# 将图例添加到当前斧头:plt.gca().legend(第一个标签,loc ='center right',bbox_to_anchor=(1,0,.4,1),框架=真)plt.show()

您需要调整 pctdistance ,直到对结果满意为止.

经过研究,我写了这个更好的(IMHO)版本:

 将matplotlib.pyplot导入为plt无花果,ax = plt.subplots()ax.axis('等于')大小= dict(第一个 = (2000, 300, 200, 100, 100, 150, 40, 30, 700),秒=(1000,200,200,400,500,40,1,1,1000),第三 = (500, 300, 400, 500, 400, 100, 5, 2, 800))百分位数= dict(first = [x * 100/sum(sizes ['first'])对于x的sizes ['first']],second = [x*100/sum(sizes['second']) for x in size['second']],第三= [x * 100/sum(sizes ['third'])对于x的大小['third']])标签 = 字典(first = [f"{x:.2f}%" if x > .5 else '' for x in percentiles['first']],second = [f"{x:.2f}%" if x > .5 else '' for x in percentiles['second']],第三 = [f"{x:.2f}%" 如果 x > .5 else '' for x in percentiles['third']])宽度 = 0.35半径= 1.5首先,_ = ax.pie(尺寸['第一个'],起始角=90,半径=半径,labeldistance = .9,标签=标签['第一个'],旋转标签=真)第二,_ = ax.pie(尺寸['第二'],radius = radius-宽度,startangle = 90,labeldistance = .9,标签=标签['第二'],rotationlabels =真)第三,_ = ax.pie(尺寸['第三'],radius = radius-2 * width,startangle = 90,labeldistance = .9,标签=标签['第三'],旋转标签=真)plt.setp(第一+第二+第三,width = width,edgecolor ='white')plt.show()

I would like to add percentage values for each of the labels and layers within my three-layered donut plot.

The following code generates the three layer donut plot and legend appropriately. However, it messes up the display of the percentage values (see output figure at bottom of this question).

Current solutions at stack overflow or elsewhere only work for adding percentage values to pie/donut chart (eg: How do I use matplotlib autopct? ) but I have three layers/levels to my pie/donut chart. My code follows below:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
fig.set_figheight(7)
fig.set_figwidth(22)

ax1 = fig.add_subplot(121)

first_labels = ["Bonjovi", "Superman", "Darius_royale", "Stargazer_1991_viz", "Obligatory_Vis1", "Gertrude", 'Trimbel', "Olio", "Iniwaka"]
first_sizes = [2000, 300, 200, 100, 100, 150, 40, 30, 700]

second_sizes = [1000, 200, 200, 400, 500, 40, 1, 1, 1000]

third_sizes = [500, 300, 400, 500, 400, 100, 5, 2, 800]

flatui = (sns.diverging_palette(20, 250, n=8))

bigger = plt.pie(first_sizes, colors=flatui, startangle=90, frame=True, radius = 1,
                 wedgeprops={'edgecolor':'k'}, autopct = '%1.1%%f')

smaller = plt.pie(second_sizes, colors=flatui, radius=0.9, startangle=90,
                 wedgeprops={'edgecolor':'k'}, autopct = '%1.1%%f')

smallest = plt.pie(third_sizes, colors=flatui, radius=0.8, startangle=90, 
                  wedgeprops={'edgecolor':'k'}, autopct = '%1.1%%f')

centre_circle = plt.Circle((0, 0), 0.7, color='white', linewidth=0)

plt.gca().add_artist(centre_circle)

# add legend to current ax:
plt.gca().legend(first_labels, loc='center right', bbox_to_anchor=(1,0,.4,1), frameon = True)

plt.show();

The results of the above code look as follows:

Can somebody please guide me on how to get the percentage values to display neatly within each donut ring?

解决方案

Summarizing my comments, here is the code from where I got a better graphic output and, I believe, what you are looking for:

import matplotlib.pyplot as plt
import numpy as np


# Example function that you can call from pie(autopct=autopct)
def autopct(pct):
    if pct > 0.5:
        return f'{pct:.2f}%'
    else:
        return ''


fig = plt.figure()
fig.set_figheight(7)
fig.set_figwidth(22)

ax1 = fig.add_subplot(121)

first_labels = (
    'Bonjovi',
    'Superman',
    'Darius Royale',
    'Stargazer 1991 Viz',
    'Obligatory Vis1',
    'Gertrude',
    'Trimbel',
    'Olio',
    'Iniwaka'
)
first_sizes = (2000, 300, 200, 100, 100, 150, 40, 30, 700)
second_sizes = (1000, 200, 200, 400, 500, 40, 1, 1, 1000)
third_sizes = (500, 300, 400, 500, 400, 100, 5, 2, 800)

flatui = (sns.diverging_palette(20, 250, n=8))

bigger = plt.pie(
    first_sizes,
    colors=flatui,
    startangle=90,
    frame=True,
    radius=1,
    wedgeprops={'edgecolor':'k'},
#    autopct='%.2f%%',
    autopct=autopct,
    pctdistance=1
)

smaller = plt.pie(
    second_sizes,
    colors=flatui,
    radius=0.9,
    startangle=90,
    wedgeprops={'edgecolor':'k'},
#    autopct='%.2f%%',
    autopct=autopct,
    pctdistance=.9
)

smallest = plt.pie(
    third_sizes,
    colors=flatui,
    radius=0.8,
    startangle=90,
    wedgeprops={'edgecolor':'k'},
#    autopct='%.2f%%',
    autopct=autopct,
    pctdistance=.8
)

centre_circle = plt.Circle((0, 0), 0.7, color='white', linewidth=0)

plt.gca().add_artist(centre_circle)

# add legend to current ax:
plt.gca().legend(
    first_labels,
    loc='center right',
    bbox_to_anchor=(1,0,.4,1),
    frameon=True
)

plt.show()

You will need to tweak pctdistance until you are satisfied with the result.

EDIT:

After researching a little I wrote this better (IMHO) version:

import matplotlib.pyplot as plt


fig, ax = plt.subplots()
ax.axis('equal')

sizes = dict(
    first = (2000, 300, 200, 100, 100, 150, 40, 30, 700),
    second = (1000, 200, 200, 400, 500, 40, 1, 1, 1000),
    third = (500, 300, 400, 500, 400, 100, 5, 2, 800)
)

percentiles = dict(
    first = [x*100/sum(sizes['first']) for x in sizes['first']],
    second = [x*100/sum(sizes['second']) for x in sizes['second']],
    third = [x*100/sum(sizes['third']) for x in sizes['third']]
)

labels = dict(
    first = [f"{x:.2f}%" if x >.5 else '' for x in percentiles['first']],
    second = [f"{x:.2f}%" if x >.5 else '' for x in percentiles['second']],
    third = [f"{x:.2f}%" if x >.5 else '' for x in percentiles['third']]
)

width = 0.35
radius = 1.5

first, _ = ax.pie(
    sizes['first'],
    startangle=90,
    radius=radius,
    labeldistance=.9,
    labels=labels['first'],
    rotatelabels=True
)

second, _ = ax.pie(
    sizes['second'],
    radius=radius - width,
    startangle=90,
    labeldistance=.9,
    labels=labels['second'],
    rotatelabels=True
)

third, _ = ax.pie(
    sizes['third'],
    radius=radius - 2 * width,
    startangle=90,
    labeldistance=.9,
    labels=labels['third'],
    rotatelabels=True
)

plt.setp(first + second + third, width=width, edgecolor='white')

plt.show()

这篇关于将百分比标签添加到三级甜甜圈图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆