16

I have 2 dataframes. I want to plot a histogram based on a column 'rate' for each, side by side. How to do it?

I tried this:

import matplotlib.pyplot as plt
plt.subplot(1,2,1)

dflux.hist('rate' , bins=100) 
plt.subplot(1,2,2) 
dflux2.hist('rate' , bins=100) 
plt.tight_layout() 
plt.show() 

It did not have the desired effect. It showed two blank charts then one populated chart.

Mark Ginsburg
  • 2,139
  • 4
  • 17
  • 31

1 Answers1

24

Use subplots to define a figure with two axes. Then specify the axis to plot to within hist using the ax parameter.

fig, axes = plt.subplots(1, 2)

dflux.hist('rate', bins=100, ax=axes[0])
dflux2.hist('rate', bins=100, ax=axes[1])

Demo

dflux = pd.DataFrame(dict(rate=np.random.randn(10000)))
dflux2 = pd.DataFrame(dict(rate=np.random.randn(10000)))

fig, axes = plt.subplots(1, 2)

dflux.hist('rate', bins=100, ax=axes[0])
dflux2.hist('rate', bins=100, ax=axes[1])

enter image description here

piRSquared
  • 285,575
  • 57
  • 475
  • 624
  • 3
    It worked! I also found to set a title on each I do: `axes[0].set_title('left title')` and then `axes[1].set_title('right title')` – Mark Ginsburg Jul 13 '17 at 01:31
  • @MarkGinsburg you can also set the title with the title parameter in the call to hist – piRSquared Jul 13 '17 at 01:32
  • i tried this `dflux2.hist('rate' , bins=100, ax=axes[1], title='king') ` but syntax error, it says `Unknown Property title` – Mark Ginsburg Jul 13 '17 at 01:35
  • @MarkGinsburg hmm guess I was wrong (-: good thing you figured it out – piRSquared Jul 13 '17 at 01:37
  • @piRSquared, you are the Putnam Exam Master!:) Question, what if I am doing this to 2 or 3 scatterplots, how do I make them be next to each other? This is the code I currently have for one: **bold [fig, axes = plt.subplots(1,2) plt.xlim(0,2000000) plt.ylim(0,250000) ax.scatter(Sales_Force_Before_Merger.Revenues[Booked], Sales_Force_Before_Merger.Amount[Booked], alpha=0.05, color='g') ax.set_title("Revenue vs Amount for Booked Before Merger") ax.set_xlabel("Revenue", size = 10) ax.set_ylabel("Amount", size = 10) ax.plt.xticks(fontsize=10) ax.plt.show(ax=axes[0])] ** – bernando_vialli Mar 01 '18 at 13:57
  • @mkheifetz I recommend you ask a new question. It's difficult to parse what you've posted. Not only will asking a new question give you the opportunity to state your question clearly, it also gives would be answerers an opportunity to earn reputation in answering. – piRSquared Mar 01 '18 at 19:13
  • Is is possible to do this for a line chart – fred.schwartz Dec 06 '18 at 16:56
  • I've got this code: def plot_it(Product): fig, axes = plt.subplots(1, 2) plt.plot(df_price[Product],'r-o',label='Price') plt.plot(df_rsp[Product],'b-o',label='RSP') plt.plot(df_promo[Product],'y-o',label='Promo') plt.plot(df_povrsp[Product],'g-o',label='PovRSP') plt.gcf().set_size_inches((18, 5)) plt.legend().set_visible(True) plt.tight_layout() – fred.schwartz Dec 06 '18 at 16:56