chamanthmvs
chamanthmvs

Reputation: 51

Is there any way to implement Stacked or Grouped Bar charts in plotly express

I am trying to implement a grouped-bar-chart (or) stacked-bar-chart in plotly express

I have implemented it using plotly (which is pretty straight forward) and below is code for it. There are altogether six columns in dataframe ['Rank', 'NOC', 'Gold', 'Silver', 'Bronze', 'Total']

`
trace1=go.Bar(x=olympics_data['NOC'],y=olympics_data['Gold'],marker=dict(color='green',opacity=0.5),name="Gold")
trace2=go.Bar(x=olympics_data['NOC'],y=olympics_data['Silver'],marker=dict(color='red',opacity=0.5),name="Silver")
trace3=go.Bar(x=olympics_data['NOC'],y=olympics_data['Bronze'],marker=dict(color='blue',opacity=0.5),name="Bronze")

data=[trace1,trace2,trace3]

layout = go.Layout(title="number of medals in each category for various countries",xaxis=dict(title="countries"),yaxis=dict(title="number of medals"),
                   barmode="stack")

fig = go.Figure(data,layout)

fig.show()`

Output:

enter image description here

I am expecting a similar output using plotly-express.

Upvotes: 5

Views: 16833

Answers (3)

shin
shin

Reputation: 32721

You can arrange your data to use px.bar() as in this link.

Or you can consider using relative in the barmode().

barmode (str (default 'relative')) – One of 'group', 'overlay' or 'relative' In 'relative' mode, bars are stacked above zero for positive values and below zero for negative values. In 'overlay' mode, bars are drawn on top of one another. In 'group' mode, bars are placed beside each other.

Using overlay:

import plotly.express as px
iris = px.data.iris()
display(iris)
fig = px.histogram(iris, x='sepal_length', color='species', 
                           nbins=19, range_x=[4,8], width=600, height=350,
                           opacity=0.4, marginal='box')
fig.update_layout(barmode='overlay')
fig.update_yaxes(range=[0,20],row=1, col=1)
fig.show()

enter image description here

Using relative:

fig.update_layout(barmode='relative')
fig.update_yaxes(range=[0,20],row=1, col=1)
fig.show()

enter image description here

Using group:

fig.update_layout(barmode='group')
fig.show()

enter image description here

Upvotes: 5

eddygeek
eddygeek

Reputation: 4510

Here is a reusable function to do this.

def px_stacked_bar(df, color_name='category', y_name='y', **pxargs):
    '''Row-wise stacked bar using plot-express.
       Equivalent of `df.T.plot(kind='bar', stacked=True)`
       `df` must be single-indexed'''
    idx_col = df.index.name
    m = pd.melt(df.reset_index(), id_vars=idx_col, var_name=color_name, value_name=y_name)
    return px.bar(m, x=idx_col, y=y_name, color=color_name, **pxargs)

Example use

df = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c'},
                   'B': {0: 1, 1: 3, 2: 5},
                   'C': {0: 2, 1: 4, 2: 6}})
px_stacked_bar(df.set_index('A'))

enter image description here

Upvotes: 0

nicolaskruchten
nicolaskruchten

Reputation: 27440

Yes, Plotly Express support both stacked and grouped bars with px.bar(). Full documentation with examples is here https://plot.ly/python/bar-charts/

Upvotes: 0

Related Questions