为什么在使用matplotlib的饼图中没有正确的百分比比例?

问题描述 投票:0回答:1

我对饼图中的百分比感到沮丧。我不为什么,但是饼图中的百分比是错误的。我认为绘图函数会误解绘图数据,然后在饼图中给我错误的百分比值。有什么问题?如何解决这个问题?有什么主意吗?

我的尝试和最少的数据

这里是minimal data on the public gist

我的尝试

 import pandas as pd

df=pd.read_csv('piechart.csv', encoding='utf-8')
labels = tuple(df.index)
total_sum = df['qty1_sum'].sum()
sizes=[58, 50, 66, 53, 48, 48, 34, 49, 59, 48]

fig1, ax1 =plt.subplots(figsize=(12,8))
pie = ax1.pie(sizes, wedgeprops=dict(width=0.8),  autopct= '%1.1f%%',shadow=True, startangle=90, textprops={'fontsize': 12})
tot_sum=str(total_sum) + '\n Metric Tons'
ax1.text(0., 0., tot_sum, horizontalalignment='center', verticalalignment='center')
ax1.axis('equal')
ax1.set(title="top 10 country by export")
ax1.set_axis_off()
ax1.legend(pie[0],top10_cty, loc="upper right", fontsize=20, bbox_to_anchor=(1.25, 1.25))
plt.show()

例如,当我运行代码时,每个国家/地区的百分比有误,例如,日本应该拥有29%,但在我尝试的代码中,它给了我11%的价值。为什么?如何解决这个问题?这个问题的根源在哪里?任何快速的解决方案?谢谢

为什么我坚持认为百分比错误

我手动计算了每个国家/地区的百分比,在饼图中的百分比值错误。我不知道为什么有什么想法可以追踪问题的根源吗?谢谢

python matplotlib
1个回答
0
投票

日本应该有29.97%,四舍五入为30.0%到小数点后一位。

主要问题是代码使用固定列表sizes=[58, 50, ...]而不是使用数据帧中的值。

填写用于饼图和标签的正确列:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('piechart.csv', encoding='utf-8')
total_sum = df['qty1_sum'].sum()

fig1, ax1 = plt.subplots(figsize=(12, 8))
pie = ax1.pie(df['qty1_sum'], wedgeprops=dict(width=0.8), autopct='%1.1f%%', shadow=True, startangle=90,
              textprops={'fontsize': 12})
tot_sum = str(round(total_sum)) + '\nMetric Tons'
ax1.text(0., 0., tot_sum, horizontalalignment='center', verticalalignment='center')
ax1.axis('equal')
ax1.set(title="top 10 country by export")
ax1.set_axis_off()
ax1.legend(pie[0], df['cty_ptn'], loc="upper right", fontsize=20, bbox_to_anchor=(1.25, 1.25))
plt.tight_layout()
plt.show()

resulting plot

© www.soinside.com 2019 - 2024. All rights reserved.