How do I display a grouped graph using a CSV file

Viewed 55

enter image description here

import pandas as pd
import plotly
import plotly.express as px
import plotly.io as pio

df = pd.read_csv("final_spreadsheet.csv")

barchart = px.bar(
    data_frame = df,
    x = "Post-Lockdown Period (May - September)",
    y = "Post-Lockdown Period (May - September)",
    color = "Peak-Lockdown Period (March-May)",
    opacity = 0.9,
    orientation ="v",
    barmode = 'relative',
)
pio.show(barchart)

I want the x axis to be the different behavioral variables and for each behavioral variable I want there to be two bars one for peak pandemic and one for post pandemic. I also want the y axis to just be the values of each

This is my current attempt but no graphs appear. Attached is also a picture of the CSV file in excel form

1 Answers

In plotly.express you can create a grouped bar chart by passing a list of the two variables you want to group together in the argument y. In your case, you'll want to pass the argument y = ['Peak-Lockdown Period (March-May)','Post-Lockdown Period (May-September)'] as well as the argument barmode = 'grouped' to px.bar. I created a sample DataFrame to illustrate:

import pandas as pd
import plotly.express as px
import plotly.io as pio

# df = pd.read_csv("final_spreadsheet.csv")

## create example DataFrame similar to yours
df = pd.DataFrame({
    'Behavioral': list('ABCD'),
    'Peak-Lockdown Period (March-May)': [76.7,26.12,0,2.94],
    'Post-Lockdown Period (May-September)': [77.32,26.38,0,3.36]
})


barchart = px.bar(
    data_frame = df,
    x = 'Behavioral',
    y = ['Peak-Lockdown Period (March-May)','Post-Lockdown Period (May-September)'],
    # color = "Peak-Lockdown Period (March-May)",
    opacity = 0.9,
    orientation ="v",
    barmode = 'group',
)

pio.show(barchart)

EDIT: you can accomplish the same thing using plotly.graph_objects:

import plotly.graph_objects as go

fig = go.Figure(data=[
    go.Bar(name='Peak-Lockdown Period (March-May)', x=df['Behavioral'].values, y=df['Peak-Lockdown Period (March-May)'].values),
    go.Bar(name='Post-Lockdown Period (May-September)', x=df['Behavioral'].values, y=df['Post-Lockdown Period (May-September)'].values),
])  

enter image description here

Related