从 pandas 数据框中制作多个饼图(每行一个) [英] Making multiple pie charts out of a pandas dataframe (one for each row)

查看:94
本文介绍了从 pandas 数据框中制作多个饼图(每行一个)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框(df),显示与各种业务类别相关的情绪:

I have a dataframe (df) that shows emotions associated with various categories of business:

我的任务是创建饼图,显示每种业务类型的情绪百分比。因此,我需要在matplotlib中创建一个读取业务列的函数,然后使用该数据框中每一行的每个情感类别构建一个饼图。

My task is to create pie charts showing the % of emotions for each type of business. So I need to create a function in matplotlib that reads the "Business" column and then builds a pie chart using each of the emotion categories for each row in the dataframe.

我已经建立了一个条形图,但是饼形图没有运气。编辑:这是我的条形图代码:

I've already built a bar plot, but I am having no luck with the pie chart. HERE IS MY CODE FOR THE BAR PLOT:

import pandas as pd
import csv
import matplotlib.pyplot as plt
GraphData = open("barGraph.csv")
df = pd.read_csv('barGraph.csv')
ax = df.plot(kind='bar', title ="Emotions at Various Businesses", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Business Type",fontsize=12)
ax.set_ylabel("Strength of Emotion",fontsize=12)
ax.set_xticklabels(['Beauty & Spas', 'Burgers-Restaurants', 'Pizza', 'Mexican Restaurants', 'Modern European-Restaurants', 'Chinese'])
plt.show()

我已经阅读了关于Pie的文档图表,但这对我来说没有任何意义,至少因为它涉及从数据框而非系列中提取数据。

I've read the documentation on pie charts, but it isn't making sense to me, at least as it pertains to drawing the data from a dataframe as opposed to a series.

有什么建议吗?

推荐答案

考虑数据框 df

df = pd.DataFrame(dict(
        Business='Beauty & Spas;Burgers-Restaurants;Pizza;Mexican Restaurants;Modern European-Restaurants;Chineese'.split(';'),
        aniticipation=[0] * 6,
        enjoyment=[6., 1., 6., 33.,150., 19.5],
        sad=[1., 2., 1., 3., 13.5, 0.],
        disgust=[1, 1, 0, 3, 37, 3],
        anger=[1.5, 2., 4., 9., 19., 3.],
        surprise=[3, 0, 0, 2, 12, 1],
        fear=[0, 1, 1, 9, 22, 1],
        trust=[0] * 6
    ))

您可以创建这样的饼图

fig, axes = plt.subplots(2, 3, figsize=(10, 6))

for i, (idx, row) in enumerate(df.set_index('Business').iterrows()):
    ax = axes[i // 3, i % 3]
    row = row[row.gt(row.sum() * .01)]
    ax.pie(row, labels=row.index, startangle=30)
    ax.set_title(idx)

fig.subplots_adjust(wspace=.2)

< a href = https://i.stack.imgur.com/bdqO7.png rel = noreferrer>

这篇关于从 pandas 数据框中制作多个饼图(每行一个)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆