簡體   English   中英

使用python / pandas / seaborn將分類數據繪制成相對頻率的單個條形圖

[英]Plotting categorical data into a single bar plot of relative frequency with python/pandas/seaborn

我從調查中得到了一堆分類數據,我想以與此處所示相同的方式繪制它。 實際上它是一個條形餅圖。

數據在熊貓數據框中,這是我試圖做的玩具示例:

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

這會產生一種堆疊的直方圖,但每個類別都不是按比例表示的。 每個柱都被過度繪制而不是繪制為小數份額。

這是沿着正確的方向嗎?

首先,您沒有正確使用子圖,請參閱此處: http//matplotlib.org/examples/pylab_examples/subplots_demo.html

其次,可以使用pandas的基本繪圖功能繪制堆積條形圖:

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

請注意,對於要堆疊的條形圖,您必須轉置數據,並且為了轉置pandas系列,您需要先將其轉換為數據框。

stacked_bars

最后,如果你絕對想要使用Seaborn,這個鏈接可能有所幫助: http//randyzwitch.com/creating-stacked-bar-chart-seaborn/

不是最優雅,但這將有效:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM