Reputation: 51
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:
I am expecting a similar output using plotly-express.
Upvotes: 5
Views: 16833
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()
Using relative
:
fig.update_layout(barmode='relative')
fig.update_yaxes(range=[0,20],row=1, col=1)
fig.show()
Using group
:
fig.update_layout(barmode='group')
fig.show()
Upvotes: 5
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'))
Upvotes: 0
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