Home > Net >  Plotting histograms on top of each other with legend (Pandas)
Plotting histograms on top of each other with legend (Pandas)

Time:07-28

I'm plotting histograms on top of each other like so:

import numpy as np
import matplotlib.pyplot as plt
import pandas


np.random.seed(0)
df = pandas.DataFrame(np.random.normal(size=(37,2)), columns=['A', 'B'])
df_2 = pandas.DataFrame(np.random.normal(size=(39,2)), columns=['C', 'D'])

df['A'].hist()
df_2['C'].hist()

plt.show()

I'm looking for a way to add legends (e.g. the purple bars = Serie 1 and the blue bars = Serie 2) but I can't find a way to do so. I should probably do something with ax = df['A'].hist() but I'm not sure I fully understand how to do it.

CodePudding user response:

You can achieve this with the following one-liner:

pd.concat([df['A'],df_2['C']],axis=1).plot(kind='hist')

  • Related