Septimus G
Septimus G

Reputation: 103

Python: Plot a histogram with colored categories

Seaborn offers the pairplot utility in which the diagonal will provide a histogram with colored categories. See the second example in the documentation. I am trying to generate a single histogram where the bars are colored by a given category, but so far I have not been able to. Here is what I have tried:

First, I tried to extract the plot, for example:

iris = sns.load_dataset("iris")
g = sns.pairplot(iris, hue="species")
ax = g.diag_axes[0]
ax.plot()

Which does not work, since the ax object behaves as emtpy. Alternatively I have not found any direct way of plotting this type of histogram directly. I tried:

 g = sns.pairplot(iris, hue="species", vars=['sepal_length'])

Which will generate only one histogram, but the y ticks are not correct, and I am not able to change them.

Upvotes: 1

Views: 2795

Answers (1)

Septimus G
Septimus G

Reputation: 103

I found that matplotlib offers this functionality directly, as illustrated here. Here is the solution for the iris dataset example:

x = [iris.sepal_length[iris.species==sp_name] for sp_name in ['setosa', 'versicolor', 'virginica']]
plt.hist(x, 8, density=True, histtype='bar', stacked=True)

Upvotes: 2

Related Questions