Pandas的重叠图例用饼图绘制

2024-10-01 07:27:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pandas plot函数绘制饼图,并使用以下代码和matplotlib:

plt.figure(figsize=(16,8))
# plot chart
ax1 = plt.subplot(121, aspect='equal')
dfhelp.plot(kind='pie', y = 'Prozentuale Gesamt', ax=ax1, autopct='%1.1f%%',
            startangle=90, shadow=False, labels=dfhelp['Anzahl Geschäfte in der Gruppe'], legend = False, fontsize=14)
plt.show

输出如下所示:

enter image description here

问题是,百分比和图例是重叠的,你有办法解决吗?对于绘图,我使用了这个question


Tags: 函数代码falsepandasplotmatplotlibchart绘制
1条回答
网友
1楼 · 发布于 2024-10-01 07:27:07

在我看来,这是this answer的一个更容易阅读的版本(但要归功于这个答案使之成为可能)

import matplotlib.pyplot as plt
import pandas as pd

d = {'col1': ['Tesla', 'GM', 'Ford', 'Nissan', 'Other'], 
     'col2': [117, 95, 54, 10, 7]}
df = pd.DataFrame(data=d)
print(df)

# Calculate percentages points
percent = 100.*df.col2/df.col2.sum()

# Write label in the format "Manufacturer - Percentage %"
labels = ['{0} - {1:1.2f} %'.format(i,j) for i,j in zip(df.col1, percent)]

ax = df.col2.plot(kind='pie', labels=None) # the pie plot
ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle
ax.yaxis.label.set_visible(False) # disable y-axis label
# add the legend
ax.legend(labels, loc='best', bbox_to_anchor=(-0.1, 1.), fontsize=8)
plt.show()

enter image description here

相关问题 更多 >