python - 从 Pandas 数据框制作多个饼图(每行一个)

标签 python pandas matplotlib dataframe pie-chart

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

enter image description here

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

我已经构建了一个条形图,但我对饼图不满意。编辑:这是我的条形图代码:

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()

我已经阅读了关于饼图的文档,但它对我来说没有意义,至少因为它涉及从数据帧而不是系列中绘制数据。

有什么建议吗?

最佳答案

考虑数据框 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
    ))

enter image description here


你可以像这样创建饼图

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)

enter image description here

关于python - 从 Pandas 数据框制作多个饼图(每行一个),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41787006/

相关文章:

Python bool 值数组?

python - 链接分组、过滤和聚合

python - 如何拆分包含电压随时间变化的数据帧,以便它可以单独存储每个波形/位的值

python - 数据类型传输/转换

python - 安装Matplotlib : Command "python setup.py egg_info" failed with error code 1 (proposed solutions did not work)

python - PyBrain 强化学习输入缓冲区不正确

python - pyparsing 值列表的递归 (ibm Rhapsody)

python - 将单独的 1D np.arrays 转换为 2D np.arrays 列表

python - Matplotlib - 以 A4 格式拟合所有子图

python - 在 matplotlib 中绘制双变量高斯分布