How to create facets in matplotlib in Python like you can in ggplot2 in R?

Viewed 590

I have a plot in ggplot2 (R) that I want to replicate using matplotlib (Python):

ggplot(data = sca, aes(x = Total_Value)) + geom_density() + facet_wrap(~Era) + theme_minimal()

How can I recreate this using matplotlib, and additionally, how could I overlay the density plots over one another (color coded) in either language/library?

Thank you.

Attached is the image.

1 Answers

The simplest way to recreate ggplot2 facets is using seaborn:

pip install seaborn

Depending on the plot type, use one of seaborn's figure-level functions:

So for density facets, use seaborn.displot with kind='kde':

  • Sample data

    import pandas as pd
    import numpy as np
    df = pd.DataFrame({'Era': np.random.choice(range(1960, 2180, 20), 200), 'Total_Value': np.random.random(200)})
    
    #       Era  Total_Value
    # 0    2140     0.479988
    # 1    2100     0.232373
    # 2    2060     0.801881
    # ..    ...          ...
    # 199  2140     0.823781
    
  • Set col='Era' for a grid

    import seaborn as sns
    sns.displot(data=df, kind='kde', x='Total_Value', col='Era', col_wrap=4)
    

  • Set hue='Era' for overlays

    import seaborn as sns
    sns.displot(data=df, kind='kde', x='Total_Value', hue='Era', palette='Purples')
    

Related