mercredi 22 juin 2016

Seaborn histogram with 4 panels (2 x 2) in Python


I'm trying to recreate this image using sklearn.datasets.load_iris and seaborn. I really like the idea of doing fig, ax = plt.subplots() and then using seaborn's ax=ax attribute. I can't figure out how to recreate this plot: enter image description here

I checked on stackoverflow and found this but it overlays them How To Plot Multiple Histograms On Same Plot With Seaborn

Here's my code and plot:

# Iris Dataset
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()

%matplotlib inline 

DF_data = pd.DataFrame(load_iris().data, 
                       columns = load_iris().feature_names, 
                       index = ["iris_%d" % i for i in range(load_iris().data.shape[0])])

Se_targets = pd.Series(load_iris().target, 
                       index = ["iris_%d" % i for i in range(load_iris().data.shape[0])], 
                       name = "Targets")

#Visualizing Iris Data
D_targets = {0: 'Iris-Setosa',
            1: 'Iris-Versicolor',
            2: 'Iris-Virgnica'}

D_features = {0: 'sepal length [cm]',
              1: 'sepal width [cm]',
              2: 'petal length [cm]',
              3: 'petal width [cm]'}

fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(8, 6))

idx_feature = 0

#Plot on 2 x 2 ax object

for i in range(ax.shape[0]):
    for j in range(0, ax.shape[1]):
        for idx_target, label_target  in list(D_targets.items()):
            sns.distplot(DF_data.as_matrix()[Se_targets==idx_target, idx_feature],
                         label=D_features[idx_feature],
                         kde=False,
                         bins=10,
                         ax=ax[i][j])        
        idx_feature += 1 

plt.legend(loc='upper right', fancybox=True, fontsize=8)

plt.tight_layout()
plt.show()

My plot is looking pretty bad:

enter image description here

UPDATE:

In response to @Cel answer, I've achieved this plot but I haven't been able to fix the labels and darken the lines around the plots.

enter image description here


Aucun commentaire:

Enregistrer un commentaire