Adding group bar charts as subplots in plotly

Kareem Ergawy picture Kareem Ergawy · May 4, 2016 · Viewed 7.4k times · Source

I want to create grouped (barmode='group') bar chart subplots in plotly. Now the problem is that plotly doesn't create bar charts as traces. Instead grouped bar charts are created as lists of Bar traces. Because of this, I don't know how to create a figure that contains grouped bar charts as subplots (i.e. add a grouped bar chart using figure.append_trace()).

For example, how can I create subplots using bar charts created in this sample:

import plotly.plotly as py
import plotly.graph_objs as go
trace1 = go.Bar(
    x=['giraffes', 'orangutans', 'monkeys'],
    y=[20, 14, 23],
    name='SF Zoo'
)
trace2 = go.Bar(
    x=['giraffes', 'orangutans', 'monkeys'],
    y=[12, 18, 29],
    name='LA Zoo'
)
data = [trace1, trace2]
layout = go.Layout(
    barmode='group'
)
fig = go.Figure(data=data, layout=layout)
plot_url = py.plot(fig, filename='grouped-bar')

Answer

ScottieB picture ScottieB · Feb 2, 2017

YES! New to plot.ly and had this issue, and as mentioned in my comment, I couldn't just do it in pandas/matplotlib for various reasons. But through the magic of subplots, you can in fact recreate multi-trace plots by just subploting them together. enter image description here

import plotly.plotly as py
import plotly.graph_objs as go
from plotly import tools

trace1 = Bar(
    x=['giraffes', 'orangutans', 'monkeys'],
    y=[20, 14, 23],
    name='SF Zoo'
)
trace2 = Bar(
    x=['giraffes', 'orangutans', 'monkeys'],
    y=[12, 18, 29],
    name='LA Zoo'
)
trace3 = Scatter(
  x=['giraffes', 'orangutans', 'monkeys']
  ,y=[33,20,17]
  ,name='subplots ftw'
  )


fig = tools.make_subplots(rows=2, cols=1, shared_xaxes=True)

fig.append_trace(trace3, 1,1)
fig.append_trace(trace1, 2, 1)
fig.append_trace(trace2,2,1)


fig['layout'].update(height=600, width=600)
iplot(fig)