1

I have a dataframe that looks like this:

df = pd.DataFrame(columns=["type", "App","Feature1", "Feature2","Feature3",
                           "Feature4","Feature5",
                           "Feature6","Feature7","Feature8"], 
                  data=[["type1", "SHA",0,0,1,5,1,0,1,0],
                        ["type2", "LHA",1,0,1,1,0,1,1,0],
                        ["type2", "FRA",1,0,2,1,1,0,1,1],
                        ["type1", "BRU",0,0,1,0,3,0,0,0],
                        ["type2", "PAR",0,1,1,4,1,0,1,0],
                        ["type2", "AER",0,0,1,1,0,1,1,0],
                        ["type1", "SHE",0,0,0,1,0,0,1,0]])

I want to make a stacked bar with type as a hue. This is, in the x axis I want the features, and for each feature I want 2 stacked bars, one for type1 and one for type2.

For instance, here they explain how to make a stacked bar plot with seaborn when the column type is dropped. Instead, I want for each feature two stacked bars. Note: the values of App are shared for type1 and type2

For instance, if I just plot the stacked bars corresponding to type1, I get this:

enter image description here

I want to make a stacked bar plot where for each feature there are two stacked bars, one for type1, and the other one for type2

Vladimir Vargas
  • 1,744
  • 4
  • 24
  • 48
  • 1
    The `App` for each type is different in your sample. What is your expected output? – Quang Hoang Apr 08 '20 at 14:49
  • @QuangHoang In this case, it is... however, it might be the case that app is shared between types. The expected output is a total of 8x2=16 stacked bars, grouped by feature (each group contains two bars, one for type1 and for type2). The stacked bars show the amount of "apps" for each feature, e.g. for feature 3, the type2 stacked bar would be a bar of height 1 for LHA, a bar of height 2 for FRA, a bar of height 1 for PAR, and a bar of height 1 for AER. Conversely, for feature 3, the type1 stacked bar would be a bar of height 1 for SHA and a bar of height 1 for BRU – Vladimir Vargas Apr 08 '20 at 15:06
  • @QuangHoang and the colours of each app bar would be different – Vladimir Vargas Apr 08 '20 at 15:06
  • @QuangHoang I edited the question to post an image – Vladimir Vargas Apr 08 '20 at 15:10

2 Answers2

0

I don't think seaborn has a function for barplots that are both stacked and grouped. But you can do it in matplotlib itself by hand. Here is an example.

Arne
  • 9,990
  • 2
  • 18
  • 28
-1

I think what you are looking for is the melt Function

d = df.drop(columns='App')
d = d.melt('type', var_name='a', value_name='b')

sns.barplot(x='a', y='b', data=d, hue='type')
Exi
  • 320
  • 1
  • 11