Search code examples
python-3.xmatplotlibseaborndistribution

Combine different seaborn distribution plots


I am using seaborn and matplotlib with Python3 to visualize distributions of two different arrays. The code I am using is:

# Create two matrices (can be 'n' dimensional)-
x = np.random.normal(size = (5, 5))
y = np.random.normal(size = (5, 5))

# On using seaborn, it creates two different plots-
sns.displot(data = x.flatten(), label = 'x')
sns.displot(data = y.flatten(), label = 'y')

plt.legend(loc = 'best')
plt.show()

# Whereas, matplotlib merges these two distributions into one plot-
plt.hist(x = x.flatten(), label = 'x')
plt.hist(x = y.flatten(), label = 'y')

plt.legend(loc = 'best')
plt.show()

How can I get the result of merging these 2 distributions as achieved in matplotlib into seaborn?


Solution

  • Combine first your data in a pandas.DataFrame, then use displot:

    import pandas as pd
    df = pd.DataFrame({'x': x.flatten(), 'y': y.flatten()})
    sns.displot(data=df)
    

    or use directly a dictionary:

    sns.displot(data={'x': x.flatten(), 'y': y.flatten()})
    

    displot