pandas 如何绘制按一个分类列分组并按另一个分类列着色的计数条形图

rqenqsqc  于 2023-09-29  发布在  其他
关注(0)|答案(4)|浏览(137)

我有一个类似这样的框架:

Property   Name    industry
1  123     name1    industry 1
1  144     name1    industry 1
2  456     name2    industry 1
3  789     name3    industry 2
4  367     name4    industry 2
.  ...     ...      ... 
.  ...     ...      ... 
n  123     name1    industry 1

我想做一个条形图,画出每个名字有多少行,并按行业给条形图上色。我试过这样的方法:

ax = df['name'].value_counts().plot(kind='bar',
                                    figsize=(14,8),
                                    title="Number for each Owner Name")
ax.set_xlabel("Owner Names")
ax.set_ylabel("Frequency")

我得到以下结果:

我的问题是如何根据数据框中的行业列为条形图着色(并添加图例)。

yvt65v4c

yvt65v4c1#

这是我的回答:

def plot_bargraph_with_groupings(df, groupby, colourby, title, xlabel, ylabel):
    """
    Plots a dataframe showing the frequency of datapoints grouped by one column and coloured by another.
    df : dataframe
    groupby: the column to groupby
    colourby: the column to color by
    title: the graph title
    xlabel: the x label,
    ylabel: the y label
    """

    import matplotlib.patches as mpatches

    # Makes a mapping from the unique colourby column items to a random color.
    ind_col_map = {x:y for x, y in zip(df[colourby].unique(),
                               [plt.cm.Paired(np.arange(len(df[colourby].unique())))][0])}

    # Find when the indicies of the soon to be bar graphs colors.
    unique_comb = df[[groupby, colourby]].drop_duplicates()
    name_ind_map = {x:y for x, y in zip(unique_comb[groupby], unique_comb[colourby])}
    c = df[groupby].value_counts().index.map(lambda x: ind_col_map[name_ind_map[x]])

    # Makes the bargraph.
    ax = df[groupby].value_counts().plot(kind='bar',
                                         figsize=FIG_SIZE,
                                         title=title,
                                         color=[c.values])
    # Makes a legend using the ind_col_map
    legend_list = []
    for key in ind_col_map.keys():
        legend_list.append(mpatches.Patch(color=ind_col_map[key], label=key))

    # display the graph.
    plt.legend(handles=legend_list)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

yqkkidmi

yqkkidmi2#

使用seaborn.countplot

import seaborn as sns
sns.set(style="darkgrid")
titanic = sns.load_dataset("titanic")
ax = sns.countplot(x="class", data=titanic)

参考seaborn https://seaborn.pydata.org/generated/seaborn.countplot.html的文档

kmb7vmvb

kmb7vmvb3#

这可能有点太复杂了,但它确实起作用了。我首先定义了从名称到行业和从行业到颜色的Map(看起来只有两个行业,但您可以根据您的情况调整字典):

ind_col_map = {
    "industry1": "red",
    "industry2": "blue"
}

unique_comb = df[["Name","industry"]].drop_duplicates()
name_ind_map = {x:y for x, y in zip(unique_comb["Name"],unique_comb["industry"])}

然后可以通过使用上述两个Map来生成颜色:

c = df['Name'].value_counts().index.map(lambda x: ind_col_map[name_ind_map[x]])

最后,你只需要简单地将color添加到绘图函数中:

ax = df['Name'].value_counts().plot(kind='bar',
                                    figsize=(14,8),
                                    title="Number for each Owner Name", color=c)
ax.set_xlabel("Owner Names")
ax.set_ylabel("Frequency")
plt.show()

a6b3iqyw

a6b3iqyw4#

让我们使用一些dataframe整形和matplotlib:

ax = df.groupby(['industry','Name'])['Name'].count().unstack(0).plot.bar(title="Number for each Owner Name", figsize=(14,8))
_ = ax.set_xlabel('Owner')
_ = ax.set_ylabel('Frequency')

输出量:

相关问题