6

I am using pandas to create bar plot. Here is an example:

df=pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.plot(kind='bar')

I want to plot two subplots within a figure and have a and b on one bar plot and c and d on another. How do I go about this?

Further, if I wanted to include the two subplots with another subplot but not created by pandas, how to do that? So a 3x1 figure where two of the subplots are from the data frame using pandas and one without using pandas. Example Plot

Taking a second attempt at this but with some modifications.

df=pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
x=[1,2,3,4,5]
y=[1,4,9,16,25]

fig, axes = plt.subplots(figsize=(8,8),nrows=2, ncols=2)
ax1=plt.subplot(2,2,1)
plt.plot(x,y)

#ax2=plt.subplot(2,2,2)
df["b"].plot(ax=axes[0,1], kind='bar', grid=True)
df["c"].plot(ax=axes[1,0], kind='bar', grid=True)
df["d"].plot(ax=axes[1,1], kind='bar', grid=True)

ax1.grid(True)
ax1.set_ylabel('Test')
ax1.set_xlabel('Test2')

#ax2.set_ylabel('Test')

How do I add axes labels for the bar plots in my subplots? Notice I have commented out ax2=plt.subplot(2,2,2) as I was testing this but this erases the bar plot completely and add the labels. Why does it do that and how can I get around this? Below is the output with the ax2... un-commented.

Plot with the lines un-commented

Charanjit Pabla
  • 343
  • 1
  • 4
  • 15

1 Answers1

14

You can start to play from this:

%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.rand(10, 4),
                  columns=['a', 'b', 'c', 'd'])

fig, axes = plt.subplots(nrows=1, ncols=2)
df[["a","b"]].plot(ax=axes[0], kind='bar')
df[["c", "d"]].plot(ax=axes[1], kind='bar');

Then you can have a look at this

rpanai
  • 10,753
  • 2
  • 33
  • 58
  • 1
    This is helpful -- thanks alot. I have a follow-up question I posted above regarding labels for the bar plot. – Charanjit Pabla Jun 19 '18 at 16:09
  • @CharanjitPabla If my answer was usueful upvote it and, eventually, accept it. As SO policy you should ask different questions separately. Doing this it will be easy for other with the same problem to find references. – rpanai Jun 19 '18 at 16:57
  • 1
    FYI, when `nrows > 1` and `ncols > 1` then `axes` is an `n * m` array. see [here](https://stackoverflow.com/a/21967899/5491375) – aydow Dec 22 '19 at 23:44