Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotly: stacked bars only in specific subplots

I have two bar charts with two columns, created as follow:

fig = tools.make_subplots(rows=1, cols=2)
trace1 = go.Bar(x=x1 , y=y1)
trace2 = go.Bar(x=x2, y=y2)
fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 1, 1)
trace3 = go.Bar(x=x3 , y=y3)
trace4 = go.Bar(x=x4, y=y4)
fig.append_trace(trace3, 1, 2)
fig.append_trace(trace4, 1, 2)

I only want the second subplot with stacked bars. I tried the following

fig['layout']["xaxis2"].update(barmode='stack')

But this of course doesnt work. How do I apply the "stack" property to only the second subplot and not the whole figure?

Thanks

like image 516
Matias Avatar asked Jun 05 '18 08:06

Matias


People also ask

How do you use subplots in Plotly?

Simple SubplotFigures with subplots are created using the make_subplots function from the plotly. subplots module. Here is an example of creating a figure that includes two scatter traces which are side-by-side since there are 2 columns and 1 row in the subplot layout.

How do you sort a bar graph in Plotly?

In Plotly. express, we can sort a bar plot using the update_layout() function and the xaxis and yaxis parameters. In our example, we wish to sort the data based on the salary starting with the smallest to the highest salary. Hence, we need to use the xaxis parameter.


1 Answers

you can use offsetgroup = same (same number in all graphs stacked).
and in the second bar base=(first bar y)

from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(rows=1, cols=2, shared_yaxes=True)

fig.add_trace(go.Bar(name='dogs', x=[1, 2, 3], y=[4, 5, 6],
                     marker_color='blue',
                     marker=dict(color=[4, 5, 6], coloraxis="coloraxis")),
              row=1, col=1)

fig.add_trace(go.Bar(name='cats', x=[1, 2, 3], y=[1, 2, 3],
                     marker_color='yellow',
                     marker=dict(color=[4, 5, 6], coloraxis="coloraxis")),
              row=1, col=1)
female_y = [4,5,6]

fig.add_trace(go.Bar(name='female', x=[1, 2, 3], y=female_y,
                     offsetgroup=1, marker_color='green',
                     marker=dict(color=[4, 5, 6])),
              row=1, col=2)

fig.add_trace(go.Bar(name='male', x=[1, 2, 3], y=[2, 3, 5],
                     offsetgroup=1, marker_color='red',
                     base = female_y ,
                     marker=dict(color=[2, 3, 5])),
              row=1, col=2)

fig.add_trace(go.Bar(name='others', x=[1, 2, 3], y=[1, 1.2, 2.5],
                     offsetgroup=2, marker_color='rgb(0,255,255)',
                     marker=dict(color=[2, 3, 5])),
              row=1, col=2)

fig.show()

enter image description here

like image 55
Ran Cohen Avatar answered Sep 20 '22 12:09

Ran Cohen