python中带有百分比标签的圆形条形图 [英] Circular barplot in python with percentage labels

查看:77
本文介绍了python中带有百分比标签的圆形条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,对 R 几乎没有经验.

我有一个带有gut_list 和百分比的数据框.我想创建一个带有标签的圆形条形图/赛道图.我在 R ggplot 中看到了一个帖子来创建与神圣中心类似的东西.但我不确定,如何在 python 中使用 ggplot.

我想要一个与以下 R 组类似的输出.但是我想尝试使用 python 包来创建带有标记值和图例的图.

解决方案

这里有一些示例代码来创建这样一个同心圆图"又名同心圆图".

主要思想是使用piex数组来指示使用多少圆.并且一次只能放置一个 x .

I am a newbie to python and have little experience in R.

I have a data frame with gut_list and percentage. I want to create a circular barplot/race track plot with labels. I saw a post in R ggplot to create something similar with hallow center. But I am not sure, how to make use of ggplot in python.

I want a similar output as in the following R group. But I would like to try the python packages to create such plots with values labeled and with legends.

Making a circular barplot with a hollow center (aka race track plot)

Example data:

gut_list = ("Micro1", "Micro2", "Micro3", "Micro4", "Micro5", "Micro6")
percent = (2, 77, 22, 41, 21, 9)

Initial trial:

import matplotlib.pyplot as plt
from matplotlib import cm
from math import log10

gut_list = ("Micro1", "Micro2", "Micro3", "Micro4", "Micro5", "Micro6") 
percent = [2, 77, 22, 41, 21, 9]
#number of data points
n = len(percent)
#find max value for full ring
k = 10 ** int(log10(max(percent)))
m = k * (1 + max(percent) // k)

#radius of donut chart
r = 1.5
#calculate width of each ring
w = r / n 

#create colors along a chosen colormap
colors = [cm.PuBu(i / n) for i in range(n)]

#create figure, axis
fig, ax = plt.subplots()
ax.axis("equal")

for i in range(n):
    innerring, _ = ax.pie([m - percent[i], percent[i]], radius = r - i * w, startangle = 90, colors = ["white", colors[i]])
    plt.setp(innerring, width = w, edgecolor = "lightgrey")


plt.legend()
plt.show()

I still didn't manage to add the label or legends.

The expected result is (i.stack.imgur.com/hOv9q.png)

解决方案

Here is some sample code to create such a "concentric circle chart" aka "concentric rings chart".

The main idea is to use the x array of the pie to indicate how much of the circle to use. And only put one x at a time. The docs tell that if the total of x is smaller than 1, it will be taken as a percentage (otherwise everything will be summed and shown proportionally to the sum, which would make the single x 100%). counterclock=False will have the arc in the desired direction. The single x is now recalculated such that the largest arc will be the percentage as set in the percentage list.

Important to note is that both an outer radius r and an inner radius is needed. In the current code the inner radius only plays a role to calculate the width step which offsets each circle.

The pie chart can display labels on the pie parts themselves, but the automatic placement can be confusing in our case. Setting labels=['desired label'] will get the label into the legend. Setting labeldistance=None will have it not displayed on the chart. The legend can be placed such that its upper right corner is at the top center of the chart. Place it elsewhere when the percentages are too high and the arcs would overlap.

Alternatively, the text could be displayed directly next to the arcs. In data coordinates the center of the circles is at 0,0. So, y=radius-w/2 is at the center of the starting edge of each ring. The text gets right aligned and vertically centered.

import matplotlib.pyplot as plt

cathegories = ["Electronics", "Appliances", "Books", "Music", "Clothing", "Cars", "Food/Beverages", "Personal Hygiene",
               "Personal Health/OTC", "Hair Care"]
percent = [81, 77, 70, 69, 69, 68, 62, 62, 61, 60]

# number of data points
n = len(percent)
# percent of circle to draw for the largest circle
percent_circle = max(percent) / 100

r = 1.5  # outer radius of the chart
r_inner = 0.4  # inner radius of the chart
# calculate width of each ring
w = (r - r_inner) / n

# create colors along a chosen colormap
#colors = [plt.cm.plasma(i / n) for i in range(n)]
colors = plt.cm.tab10.colors

# create figure, axis
fig, ax = plt.subplots()
ax.axis("equal")

for i in range(n):
    radius = r - i * w
    ax.pie([percent[i] / max(percent) * percent_circle], radius=radius, startangle=90,
           counterclock=False,
           colors=[colors[i]],
           labels=[f'{cathegories[i]} – {percent[i]}%'], labeldistance=None,
           wedgeprops={'width': w, 'edgecolor': 'white'})
    ax.text(0, radius - w / 2, f'{cathegories[i]} – {percent[i]}% ', ha='right', va='center')

# plt.legend(loc='upper right', bbox_to_anchor=(0.5, 1.1), prop={'size': 12})
plt.tight_layout()
plt.show()

这篇关于python中带有百分比标签的圆形条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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