Neel
Neel

Reputation: 625

Pandas - Plotly subplots with grouped charts

I have following two similar data frames containing data for two different teams

dataFrameA:

name         bat_pos_1 ing_1_runs bat_pos_2 ing_2_runs
jack           2           10            2         20
john           1           20            1         5

dataFrameB:

name         bat_pos_1 ing_1_runs bat_pos_2 ing_2_runs
jill           5           20            3         30
nancy          4            5            2         7

I am using the following code to render a poltly grouped bar chart

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

figTeamARuns = go.Figure(data=[
    go.Bar(name='Ist Inning', x=dataFrameA['name'], y=dataFrameA['ing_1_runs']),
    go.Bar(name='2nd Inning', x=dataFrameA['name'], y=dataFrameA['ing_2_runs']),
   ])
figTeamARuns.update_layout(barmode='group')
figTeamARuns.show()

figTeamBRuns = go.Figure(data=[
    go.Bar(name='Ist Inning', x=dataFrameB['name'], y=dataFrameB['ing_1_runs']),
    go.Bar(name='2nd Inning', x=dataFrameB['name'], y=dataFrameB['ing_2_runs']),
   ])
figTeamBRuns.update_layout(barmode='group')
figTeamBRuns.show()

The above code renders two charts one below the other but I want same charts to appear side by side. I know that i can be done using plotly subplots but I don't know how to go about it. Here is code I am trying to use

figFinalBatting = go.Figure()
figFinalBatting = make_subplots(rows=1, cols=2)

I am stuck on what to do next. Any ideas?

Upvotes: 0

Views: 1319

Answers (1)

rpanai
rpanai

Reputation: 13437

I think that the docs is quite clear here. Once you define fig you need to add every trace and specify in with row, col of the subplot scheme you want it to appear.

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

fig = make_subplots(rows=1, cols=2)
fig.add_trace(
    go.Bar(name='Ist Inning',
           x=dataFrameA['name'],
           y=dataFrameA['ing_1_runs']),
    row=1, col=1)

fig.add_trace(
    go.Bar(name='2nd Inning',
           x=dataFrameA['name'],
           y=dataFrameA['ing_2_runs']),
    row=1, col=1)

fig.add_trace(
    go.Bar(name='Ist Inning',
           x=dataFrameB['name'],
           y=dataFrameB['ing_1_runs']),
    row=1, col=2)

fig.add_trace(
    go.Bar(name='2st Inning',
           x=dataFrameB['name'],
           y=dataFrameB['ing_2_runs']),
    row=1, col=2)

fig.show()

Upvotes: 2

Related Questions