在matplotlib python中调整嵌套饼图

2w3kk1z5  于 2023-11-22  发布在  Python
关注(0)|答案(1)|浏览(112)
sales_gender = current_employees.groupby("gender")['amount'].mean()

male_college = current_employees.loc[(current_employees['gender'] == 0)]

female_college = current_employees.loc[(current_employees['gender'] == 1)]

male_college = male_college.groupby("college")["gender"].count()

male_college = male_college.tolist()

female_college = female_college.groupby("college")["gender"].count()
female_college = female_college.tolist()

gender_college = male_college + female_college
gender_college

gender = ["Male","Female"]

gender_college_label = [ "Male Degree","Female No Degree", "Female Degree","Male No Degree",]

plt.figure(1)
plt.figure(figsize=(20, 8))

size = 0.3
plt.rcParams['font.size'] = 9.0
cmap = plt.colormaps["tab20c"]
outer_colors = cmap(np.arange(3)*4)
inner_colors = cmap([1, 2, 5, 6, 9, 10])

plt.pie(sales_gender, radius=1, colors=outer_colors, wedgeprops=dict(width=size, edgecolor='w'), 
    labels=gender, autopct='%1.1f%%', pctdistance=(1-size/2), textprops={'fontsize': 12})

plt.pie(gender_college, radius=1-size, colors=inner_colors, wedgeprops=dict(width=size, edgecolor='w'), 
    labels=gender_college, labeldistance=0.7, pctdistance=(1-size/2), textprops={'fontsize': 12})

plt.title('Sales Performance by Gender & Number of Gender with degrees or not',fontsize=12, fontweight='bold')

plt.legend(handles[1:], gender_college_label, loc=(0.9, 0.1))

plt.show()

字符串
这是我使用matplotlib创建嵌套饼图的代码,图像是输出


的数据
我希望这两个饼图是相互内联,使例子36和9将完全符合橙子49.6%的女性和33和8将完全符合50.4%的男性
这是可能的,而不使用任何其他库,并保持解决方案尽可能简单?

q9rjltbz

q9rjltbz1#

我认为你必须直接修改楔形。给出以下代码:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

size = 0.3
vals = [60, 40]
vals2 = [70, 30]

cmap = plt.colormaps["tab20c"]
outer_colors = cmap(np.arange(3) * 4)
inner_colors = cmap([1, 10])

ax.pie(
    vals,
    radius=1,
    colors=outer_colors,
    wedgeprops=dict(width=size, edgecolor="w"),
)

ax.pie(
    vals2,
    radius=1 - size,
    colors=inner_colors,
    wedgeprops=dict(width=size, edgecolor="w"),
)

ax.set(aspect="equal")
plt.show()

字符串
生产这个:


的数据
所以你需要像这样得到面片,并根据外部值设置它们的theta值:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

size = 0.3
vals = [60, 40]
vals2 = [70, 30]

cmap = plt.colormaps["tab20c"]
outer_colors = cmap(np.arange(3) * 4)
inner_colors = cmap([1, 10])

ax.pie(
    vals,
    radius=1,
    colors=outer_colors,
    wedgeprops=dict(width=size, edgecolor="w"),
)

wedges, *_ = ax.pie(
    vals2,
    radius=1 - size,
    colors=inner_colors,
    wedgeprops=dict(width=size, edgecolor="w"),
)
wedges[0].set_theta2((vals[0] / 100) * 360)
wedges[1].set_theta1((vals[0] / 100) * 360)

ax.set(aspect="equal")
plt.show()


下一篇:

相关问题