Search code examples
pythonpandasseaborndensity-plot

plot more vertical density plots in one graph


I would like to obtain a graph similar to the one I drew:

multiple densities

In the x axis the date of the collected data, and in the y axis the associated densities.

I wrote these few lines:

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
from datetime import datetime

df = pd.DataFrame(np.random.rand(7, 100), columns=['y']*100)
df.index = pd.date_range(datetime.today(), periods=7).tolist()

sns.kdeplot(data=df, y='y', fill=True,  alpha=.5, linewidth=0)

plt.show()

but of course it doesn't work. How can I modify the code to get what I imagined?


Solution

  • Can be done easily using statsmodels.graphics.boxplots.violinplot

    from statsmodels.graphics.boxplots import violinplot
    
    fig, ax = plt.subplots()
    violinplot(data=df.values, ax=ax, labels=df.index.strftime('%Y-%m-%d'), side='right', show_boxplot=False)
    fig.autofmt_xdate()
    

    enter image description here