【问题标题】:Plotting categorical data into a single bar plot of relative frequency with python/pandas/seaborn使用 python/pandas/seaborn 将分类数据绘制成相对频率的单个条形图
【发布时间】:2016-06-06 02:37:20
【问题描述】:

我有一堆来自调查的分类数据,我想以与 here 相同的方式绘制它。实际上它是一个条形饼图。

数据位于 pandas 数据框中,这是我尝试做的一个玩具示例:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt


# create toy dataframe
df = pd.DataFrame({'Names': ['Steve','Steve','Steve','Jon','Michael','Michael','Eric'] })


# get pd.Series of counts of each name
data_counts = df['Names'].value_counts()


# return the name of each category, and its counts separately
category_names = data_counts.index
category_counts = data_counts.get_values()


# attempt to plot
f, ax = plt.subplots(figsize=(10, 10))
colors = ['red', 'green', 'blue', 'yellow']
i=0
for name, data in zip(category_names, category_counts):

    sns.barplot(x=data, label=name, color=colors[i])
    i+=1

handles, labels = ax.get_legend_handles_labels()
ax.legend(loc='upper right', prop={'size':12})

这会产生一种堆叠直方图,但每个类别都没有按比例表示。每个条形图都被过度绘制而不是绘制为部分份额。

这是正确的路线吗?

【问题讨论】:

  • 你知道你应该accept an answer,对吧?这将对以后有类似问题的其他人有所帮助。
  • 感谢您的帮助!我不知道“接受答案”有时间限制。感谢您的提醒
  • 您实际上已经对答案进行了投票,而不是接受了它们:) 您可以投票任何好的答案,但您只能接受一个答案。您应该接受最适合您的答案(可能是主观的)。很高兴我能帮上忙!

标签: python pandas bar-chart seaborn


【解决方案1】:

首先,您没有正确使用子图,请参见此处:http://matplotlib.org/examples/pylab_examples/subplots_demo.html

其次,可以用pandas的基本绘图功能绘制堆积条形图:

pd.DataFrame(data_counts).transpose().plot(kind='barh', stacked=True)

请注意,要堆叠条形,您必须转置数据,并且要转置 pandas Series,您需要先将其转换为数据框。

最后,如果您绝对想使用 Seaborn,此链接可能会有所帮助:http://randyzwitch.com/creating-stacked-bar-chart-seaborn/

【讨论】:

    【解决方案2】:

    不是最优雅的,但这会起作用:

    x = df.Names.value_counts()
    y = x.reset_index()
    y["name_of_column"] = ""
    y.pivot(index="name_of_column", columns="index", values=0).plot(kind="bar", stacked=True)
    

    【讨论】:

      猜你喜欢
      • 2020-06-20
      • 2021-03-16
      • 2021-07-28
      • 2021-12-19
      • 1970-01-01
      • 2019-07-29
      • 2020-12-13
      • 2020-06-29
      • 1970-01-01
      相关资源
      最近更新 更多