Search code examples
pythonbar-chartaltair

Create Altair Chart of Value Counts of Multiple Columns


Using Altair charting, how can I create a chart of value_counts() of multiple columns? This is easily done by matplotlib. How can the identical chart be created using Altair?

import matplotlib.pyplot as plt 
import pandas as pd 

df = pd.DataFrame({'Col1':[0,1,2,3], 
               'Col2':[0,1,2,2], 
               'Col3':[2,3,3,3]}) 

pd.DataFrame({col:df[col].value_counts(normalize=True) for col in df}).plot(kind='bar')

enter image description here


Solution

  • You could do this:

    import pandas as pd 
    import altair as alt
    
    
    df = pd.DataFrame({
        'Col1':[0,1,2,3], 
        'Col2':[0,1,2,2], 
        'Col3':[2,3,3,3]
    }).melt(var_name='column')
    
    alt.Chart(df).mark_bar().encode(
        x='column',
        y='count()',
        column='value:O',
        color='column'
    )
    

    enter image description here

    In the next major release of Altair you can use the offset channels instead of faceting as in this example.