简体   繁体   English

使用seaborn和matplotlib的堆积条形图

[英]stacked bar chart using seaborn and matplotlib

I am new to pandas and matplotlib and trying to accomplish following. 我是熊猫和matplotlib的新手,正在尝试完成以下工作。 I have a data frame as shown below which is actually a listing the performance of players based on match date 我有一个数据框,如下所示,它实际上是根据比赛日期列出的球员表现

name          runs  match_date  player_id
Dockrell, G H   0   2018-06-17  3752
Stirling, P R   81  2018-06-17  3586
O'Brien, K J    28  2018-06-17  3391
McCarthy, B J   0   2018-06-17  4563
Poynter, S W    0   2018-06-17  4326
Poynter, S W    2   2018-06-17  4326
McCarthy, B J   0   2018-06-17  4563
Shannon, J N K  5   2018-06-17  4219
Shannon, J N K  6   2018-06-17  4219
Stirling, P R   51  2018-06-17  3586

This is a subset of data that I have created based on following code 这是我根据以下代码创建的数据子集

match_performance = dataFrame[['name','runs','match_date','player_id']].sort_values('match_date',ascending=False).groupby('player_id').head(5)
sns.set_context({"figure.figsize": (10, 4)})
ax = sns.barplot(x="name", y="runs",  data=match_performance)
ax.set_xticklabels(ax.get_xticklabels(), rotation=90) 

结果图 I need to plot this either as stacked bar or grouped bar to display performance of players in there last 5 matches based on player id which I have in the dataframe but I am not sure how to go about plotting this data as required. 我需要将其绘制为堆积条形图或分组条形图,以根据我在数据帧中拥有的玩家ID来显示最近5场比赛中玩家的表现,但我不确定如何根据需要绘制此数据。

Michael Waskom, the creater of Seaborn posted this on Twitter: Seaborn的创建者Michael Waskom在Twitter上发布了此信息:

@randyzwitch I don't really like stacked bar charts, I'd suggest maybe using pointplot / factorplot with kind=point @randyzwitch我不太喜欢堆积的条形图,建议您将pointplot / factorplot与kind = point一起使用

— Michael Waskom (@michaelwaskom) September 4, 2014 — Michael Waskom(@michaelwaskom)2014年9月4日

Regretfully, the answer is no. 遗憾的是,答案是否定的。 There is no built-in function in Seaborn for plotting stacked bar charts. Seaborn中没有内置功能可以绘制堆积的条形图。

While this is an older question I found it while looking for a solution, so I hope this may help someone. 虽然这是一个较旧的问题,但我在寻找解决方案时发现了它,所以希望对您有所帮助。 Achieving stacked bars are a bit tricky with seaborn, but this should do the trick 对于seaborn而言,实现堆叠的条形有点棘手,但这应该可以解决问题

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

def stacked_chart_sns(df, x, y, group_by, palette):
    array_of_dfs = []
    w_0 = None
    for u in df[group_by].unique():
        w = df[df[group_by] == u].copy()
        if w_0 is not None:
            w = w.merge(w_0, how='outer').fillna(0)
            w[group_by] = u
            w[y] = w.apply(lambda x: x[y] + x['y_prev'], axis=1)
            w = w.drop(columns=['y_prev'])
        array_of_dfs += [w]
        w_0 = w.drop(columns=[group_by]).rename(columns={y:'y_prev'}).copy()

    patches = []
    for i, d in enumerate(array_of_dfs[::-1]):
        sns.barplot(x=x, y=y, data=d, color=palette[i])
        patches += [mpatches.Patch(label=list(df[group_by].unique())[::-1][i], color=palette[i])]

    plt.legend(handles=patches, loc = 'upper left', ncol=1, labelspacing=1)
    plt.show()

### use it with - for the example data in the question:
stacked_chart_sns(match_performance, 'match_date', 'runs', 'player_id', sns.color_palette("Spectral"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM