SJJ
SJJ

Reputation: 25

How to make a multiple bar chart?

How to make a bar chart using 'altair' to use the information in a table?

If you need to change the table format is it ok, I want to make a bar chart as below. (My end goal is to create a bar chart in streamlit.)

Example,

import pandas as pd
import streamlit as st

df = pd.DataFrame([['sst', '100', '1000'],['can','500','600']], columns=['model','0','1'])
st.bar_chart(df, ??)

enter image description here

How to make a this chart?

Upvotes: 1

Views: 2185

Answers (1)

Natalia Goloskokova
Natalia Goloskokova

Reputation: 231

as step 1 - you need to melt your dataframe, so that it would consist only of 3 columns, model, variable (0/1) and value. Step 2 - Grouped bar chart - is nothing than 2 individual bar charts for each model, stack together as columns.

Step 3 - final tweaks: Additional chart configuration to make it look as a single chart:

  • spacing between 2 columns - here it is 0.
  • Padding inside each chart - to add some breathing space between models and keeping grid lines at the same time
  • with a stroke opacity =0 - we remove frames around each chart to keep an impression of a single image.
import pandas as pd
import altair as alt
import streamlit as st

df = pd.DataFrame([['sst', '100', '1000'],['can','500','600']], columns=['model','0','1'])

#transform dataframe 
source=pd.melt(df, id_vars=['model'])

chart=alt.Chart(source).mark_bar(strokeWidth=100).encode(
    x=alt.X('variable:N', title="", scale=alt.Scale(paddingOuter=0.5)),#paddingOuter - you can play with a space between 2 models 
    y='value:Q',
    color='variable:N',
    column=alt.Column('model:N', title="", spacing =0), #spacing =0 removes space between columns, column for can and st 
).properties( width = 300, height = 300, ).configure_header(labelOrient='bottom').configure_view(
    strokeOpacity=0)

st.altair_chart(chart) #, use_container_width=True)

enter image description here

Upvotes: 1

Related Questions