i create following histogram (see image below) taken book "think stats". however, cannot them on same plot. each dataframe takes own subplot.
i have following code:
import nsfg import matplotlib.pyplot plt df = nsfg.readfempreg() preg = nsfg.readfempreg() live = preg[preg.outcome == 1] first = live[live.birthord == 1] others = live[live.birthord != 1] #fig = plt.figure() #ax1 = fig.add_subplot(111) first.hist(column = 'prglngth', bins = 40, color = 'teal', \ alpha = 0.5) others.hist(column = 'prglngth', bins = 40, color = 'blue', \ alpha = 0.5) plt.show()
the above code not work when use ax = ax1 suggested in: pandas multiple plots not working hists nor example need: overlaying multiple histograms using pandas. when use code is, creates 2 windows histograms. ideas how combine them?
here's example of how i'd final figure look:
as far can tell, pandas can't handle situation. that's ok since of plotting methods convenience only. you'll need use matplotlib directly. here's how it:
%matplotlib inline import numpy np import matplotlib.pyplot plt import pandas #import seaborn #seaborn.set(style='ticks') np.random.seed(0) df = pandas.dataframe(np.random.normal(size=(37,2)), columns=['a', 'b']) fig, ax = plt.subplots() a_heights, a_bins = np.histogram(df['a']) b_heights, b_bins = np.histogram(df['b'], bins=a_bins) width = (a_bins[1] - a_bins[0])/3 ax.bar(a_bins[:-1], a_heights, width=width, facecolor='cornflowerblue') ax.bar(b_bins[:-1]+width, b_heights, width=width, facecolor='seagreen') #seaborn.despine(ax=ax, offset=10)
and gives me:
Comments
Post a Comment