Pandas: plotting two histograms on the same plot

I would like to see two histograms displayed on the same plot (with different colors and possibly with alpha-alphas). I tried

import random
x = pd.DataFrame([random.gauss(3,1) for _ in range(400)])
y = pd.DataFrame([random.gauss(4,2) for _ in range(400)])


x.hist( alpha=0.5, label='x')
y.hist(alpha=0.5, label='y')
x.plot(kind='kde', style='k--')
y.plot(kind='kde', style='k--')

plt.legend(loc='upper right')
plt.show()

      

This gives the result in 4 different graphs. How can I use them on the same?

+3


source to share


2 answers


If I understand correctly, both hists should go into the same subplot. So this should be

fig = plt.figure()
ax = fig.add_subplot(111)
_ = ax.hist(x.values)
_ = ax.hist(y.values, color='red', alpha=.3)

      

You can also pass the pandas plot method of the axis object, so if you want both kde on the other graph to do:



fig = plt.figure()
ax = fig.add_subplot(111)
x.plot(kind='kde', ax=ax)
y.plot(kind='kde', ax=ax, color='red')

      

To get everything in one plot, you need two different y-scales, since kde is density and histogram is frequency. To do this, you use the command axes.twinx()

.

fig = plt.figure()
ax = fig.add_subplot(111)
_ = ax.hist(x.values)
_ = ax.hist(y.values, color='red', alpha=.3)

ax1 = ax.twinx()
x.plot(kind='kde', ax=ax1)
y.plot(kind='kde', ax=ax1, color='red')

      

+5


source


You can use plt.figure () and add_subplot () function: the first 2 arguments are the number of rows and columns you want in your plot, the last is the position of the subplot on the plot.



fig = plt.figure()
subplot = fig.add_subplot(1, 2, 1)
subplot.hist(x.ix[:,0], alpha=0.5)
subplot = fig.add_subplot(1, 2, 2)
subplot.hist(y.ix[:,0], alpha=0.5)

      

+1


source







All Articles