我有一个数据框,例如:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# Sample data
data = {
'genus': ['SpeciesA', 'SpeciesB', 'SpeciesC', 'SpeciesD', 'SpeciesE', 'SpeciesF', 'SpeciesG', 'SpeciesH'],
'count': [10, 2, 1, 1, 1, 1, 1, 1],
'Type': ['Animal', 'Environment', 'Environment', 'Environment', 'Animal', 'Animal', 'Animal/Environment', 'Animal/Environment']
}
# Create DataFrame
df = pd.DataFrame(data)
>>> df
genus count Type
0 SpeciesA 10 Animal
1 SpeciesB 2 Environment
2 SpeciesC 1 Environment
3 SpeciesD 1 Environment
4 SpeciesE 1 Animal
5 SpeciesF 1 Animal
6 SpeciesG 1 Animal/Environment
7 SpeciesH 1 Animal/Environment
我想使用 python 创建一个饼图,将饼图分为与其总计数成比例的每个类型
到目前为止我可以使用以下方法做到这一点:
# Group by 'Type' and sum up 'count' within each group
type_counts = df.groupby('Type')['count'].sum()
# Create pie chart
plt.figure(figsize=(8, 8))
plt.pie(type_counts, labels=type_counts.index, startangle=140)
plt.title('Distribution of Counts by Type')
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
但我现在正在寻找一种在特定子饼图部分中添加属标签的方法。
此类标签应以这种方式包含(A):
通过优化空间,使标签随机放置在对应的饼图中,不重叠。
或者,如果不可能简单地以这种方式放置它们(B):
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# Sample data
data = {
'genus': ['SpeciesA', 'SpeciesB', 'SpeciesC', 'SpeciesD', 'SpeciesE', 'SpeciesF', 'SpeciesG', 'SpeciesH'],
'count': [10, 2, 1, 1, 1, 1, 1, 1],
'Type': ['Animal', 'Environment', 'Environment', 'Environment', 'Animal', 'Animal', 'Animal/Environment', 'Animal/Environment']
}
# Create DataFrame
df = pd.DataFrame(data)
plt.figure(figsize=(20, 20))
fig, ax = plt.subplots()
size = 0.5
cmap = plt.get_cmap("tab20c")
outer_colors = cmap(np.arange(3)*4)
inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10]))
ax.pie(df.groupby('Type', sort=False)['count'].sum(), radius=1, colors=outer_colors, labels=df['Type'].drop_duplicates(), autopct='%1.1f%%',
wedgeprops=dict(width=size, edgecolor='w'))
ax.pie(df['count'], radius=1-size, colors=inner_colors, labels=df['genus'], autopct='%1.1f%%',
wedgeprops=dict(width=size, edgecolor='w'))
ax.set(aspect="equal", title='Distribution 1 and 2')
plt.show()