【问题标题】:Making multiple pie charts out of a pandas dataframe (one for each row)用 pandas 数据框制作多个饼图(每行一个)
【发布时间】:2017-06-06 19:42:18
【问题描述】:

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

我的任务是创建饼图,显示每种业务类型的情绪百分比。所以我需要在 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()

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

有什么建议吗?

【问题讨论】:

标签: python pandas matplotlib dataframe pie-chart


【解决方案1】:

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

【讨论】:

  • 谢谢,piRSquared。我真的很感激。
  • @AndrewSmith 你可能正在使用 jupyter notebook,你需要运行 '%matplotlib inline'
  • 是的,完全正确。为什么 Jupyter 需要内联格式?
  • @piRSquared ,这是很好的代码,谢谢。如果我也想在每个饼图中显示值。我们怎么能这样做?例如:Beauty & Spas,我们想要显示的享受是红色的 6。有什么帮助吗?
  • 伟大的工作,为我工作,我想知道你如何为整个饼图命名?
猜你喜欢
  • 1970-01-01
  • 2018-01-10
  • 1970-01-01
  • 1970-01-01
  • 2020-05-11
  • 2021-03-20
  • 1970-01-01
  • 1970-01-01
  • 2022-07-27
相关资源
最近更新 更多