Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show label names in pandas groupby histogram plot

Tags:

python

pandas

I can plot multiple histograms in a single plot using pandas but there are few things missing:

  1. How to give the label.
  2. I can only plot one figure, how to change it to layout=(3,1) or something else.
  3. Also, in figure 1, all the bins are filled with solid colors, and its kind of difficult to know which is which, how to fill then with different markers (eg. crosses,slashes,etc)?

Here is the MWE:

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

df = sns.load_dataset('iris')

df.groupby('species')['sepal_length'].hist(alpha=0.7,label='species')
plt.legend()

Output: enter image description here

To change layout I can use by keyword, but can't give them colors

HOW TO GIVE DIFFERENT COLORS?

df.hist('sepal_length',by='species',layout=(3,1))
plt.tight_layout()

Gives: enter image description here

like image 700
BhishanPoudel Avatar asked Sep 13 '25 17:09

BhishanPoudel


1 Answers

You can resolve to groupby:

fig,ax = plt.subplots()

hatches = ('\\', '//', '..')         # fill pattern
for (i, d),hatch in zip(df.groupby('species'), hatches):
    d['sepal_length'].hist(alpha=0.7, ax=ax, label=i, hatch=hatch)

ax.legend()

Output:

enter image description here

like image 124
Quang Hoang Avatar answered Sep 16 '25 09:09

Quang Hoang