python - 绘制带有值的饼图
问题描述
我的df在下面
sales_qtr_month = sales_qtr.groupby(['Month']).agg('sum')
Sales2015 Sales2016
Month
Q1 5.485800e+06 6.997953e+06
Q2 5.390862e+06 7.237361e+06
Q3 6.164094e+06 7.861546e+06
Q4 5.713634e+06 7.567868e+06
饼图代码
sales_qtr_month.plot.pie(figsize=(15,15),subplots=True)
- 如何将 Q1、Q2、Q3、Q4 的值添加到图表中?
解决方案
我不确定如何生成您的数据,所以我将生成类似的内容来涵盖所有步骤。
# Make some data
raw_data = {'Sales2016': [10, 20, 900, 100, 50],
'Sales2015': [10, 20, 30, 100, 50],
'Month': ['Q1', 'Q2', 'Q3', 'Q4', 'Q5']}
# Generate a dataframe
df = pd.DataFrame(raw_data, columns = ['Sales2016','Sales2015', 'Month'])
在此之后,我将运行 groupby() ,它根本不会更改数据。这个 groupby() 的目的是获取类似于 OP 给出的 DataFrameGroupBy。
df_sum = df.groupby(['Month']).agg('sum')
哪些构造
Sales2016 Sales2015
Month
Q1 10 10
Q2 20 20
Q3 900 30
Q4 100 100
Q5 50 50
从这一点开始,我会将 DataFrameGroupBy 展平并用月份对其进行索引。
df_flatten = df_sum.reset_index().set_index('Month')
steven提供的链接对如何在 matplotlib 中进行标记提供了非常好的见解。函数 pandas.DataFrame.plot.pie 包装了 matplotlib.pyplot.pie() ,因此我们可以使用该链接中的一些技术。
首先,我们声明一个将百分比转换为整数的函数。此功能类似于此链接给出的功能。我已将 round() 添加到函数中,这样它就不会给出错误的数字(例如 int(889.99) = 899 但我们想要 900)
# Covert percent and total to value
def func(pct, allvals):
absolute = int(round(pct/100*np.sum(allvals)))
return "${:.1f}".format(absolute)
现在我们可以用标签绘制饼图,我们可以指定类似于链接中的 autopct
f, axes = plt.subplots(1,2, figsize=(10,10))
for ax, col in zip(axes, df_flatten.columns):
print(col)
df_flatten[col].plot(kind='pie', autopct=lambda pct: func(pct, df_flatten[col].tolist()), labels=df_flatten.index, ax=ax, title=col, fontsize=10)
ax.legend(loc=3)
您的标签现在应该出现了。
推荐阅读
- swift - 来自字符串 Swift 的所有其他字符
- python - NameError:名称'createGame'未定义未导入
- python - 将 2 个不同年份的 .resample(D).size() 绘制到一张图表中?
- javascript - document.getElementById([id]).value 返回一个空字符串
- react-native - Monorepo - 获取根目录下的包内的图像(反应原生)
- class - 是否可以在 Fortran 中使类实例可调用?
- bash - Terraform - 本地供应商提示输入 - bash 脚本
- python - requests_html TimeoutError: Navigation Timeout Exceeded: 超过 9000 ms
- python - 我可以在 matplotlib 中使用 scatter 函数而不指定 x 轴吗?
- javascript - 警报返回未定义(js)