15

I want to plot two pandas dataframes side by side, each plot should be in subplot form. I am using following lines:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# create dummy pandas dataframes
pd1 = pd.DataFrame({'a':np.random.random(22),'b':np.random.random(22),'c':np.random.random(22)})
pd2 = pd.DataFrame({'J':np.random.random(22),'K':np.random.random(22),'P':np.random.random(22)})
#create subplot figure with having two side by side plots
fig, axes = plt.subplots(nrows=1,ncols=2,figsize=(12,6))
# plot first pandas frame in subplot style
pd1.plot(ax = axes[0],subplots=True) 
# plot second pandas frame in subplot style
pd2.plot(ax = axes[1],subplots=True)

Without subplot option, side by side plots are drawn but I want in subplot style. Is there any other option to get it done?

Precisely, I want to plot pandas in the following manner: enter image description here

2
  • 1
    What is "subplot style"? Please describe what you want to achieve. Commented Feb 27, 2018 at 10:46
  • I have updated my question with a figure Commented Feb 27, 2018 at 11:08

1 Answer 1

31

You need a subplot grid of 3 rows and 2 columns to host your plot. Then the ax argument needs to take the 3 axes you want to plot the 3 dataframe columns to.

fig, axes = plt.subplots(nrows=3,ncols=2)
pd1.plot(ax = axes[:,0], subplots=True) 
pd2.plot(ax = axes[:,1], subplots=True)

Complete code:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# create dummy pandas dataframes
pd1 = pd.DataFrame({'a':np.random.random(22),'b':np.random.random(22),
                    'c':np.random.random(22)})
pd2 = pd.DataFrame({'J':np.random.random(22),'K':np.random.random(22),
                    'P':np.random.random(22)})
#create subplot figure with having two side by side plots
fig, axes = plt.subplots(nrows=3,ncols=2,figsize=(12,6))
# plot first pandas frame in subplot style
pd1.plot(ax = axes[:,0],subplots=True) 
# plot second pandas frame in subplot style
pd2.plot(ax = axes[:,1],subplots=True)

plt.show()

enter image description here

2
  • I still face a problem when the two data frames have a different number of columns. I think that is a different question and I need to find some workaround for that. Commented Feb 27, 2018 at 11:49
  • 1
    You need to create the subplot grid such that it can host the number of subplots created by the dataframe plot. Then make sure the list of axes supplied to ax has exactly the number of axes as there are columns to plot. Depending on the number of columns to plot you may not be able to use plt.subplots to create the grid, but rather create the subplots one by one or using a gridspec. Commented Feb 27, 2018 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.