Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting DataFrame with column in all subplots

Consider that I have a pandas DataFrame with 3 columns. I would to plot two of these columns as separate subplots and the other one should appear on both the other subplots.

To explain better, consider the example

x = np.linspace(0,10,5)
y1 = 2*x
y2 = 3*x
y3 = 4*x

df = pd.DataFrame(index=x, data=zip(*[y1,y2,y3]))
df.plot(subplots=True, layout=(1,3), ylim=[0,40])

This code displays enter image description here

Which is close to what I want. But not exactly. I would like that plot to have only two subplots. One with columns 0 and 1, and the other with columns 0 and 2. As is comparing each column to another column. The closest I got was

df[[1,2]].plot(subplots=True, layout=(1,2), ylim=[0,40])
plt.plot(df.index, df[0], label=0)

which gives me this picture, where column 0 only appears in the second subplot, and not on all of them:

enter image description here

Is there any way to do this? Preferably not going completely outside of pandas. I know I could just iterate through columns 1 and 2 and manually plot them with pyplot alongside column 0, but that's just too much code and I'd like to avoid that, if possible.

like image 578
TomCho Avatar asked Feb 26 '16 15:02

TomCho


People also ask

How do I plot all columns in a data frame?

You can plot data directly from your DataFrame using the plot() method. To plot multiple data columns in single frame we simply have to pass the list of columns to the y argument of the plot function.

How can I plot separate pandas Dataframes as subplots?

You can manually create the subplots with matplotlib, and then plot the dataframes on a specific subplot using the ax keyword. For example for 4 subplots (2x2): import matplotlib. pyplot as plt fig, axes = plt.


1 Answers

Like this

ax = df[[1,2]].plot(subplots=True, layout=(1,2), ylim=[0,40])

for axe in ax[0]:
    axe.plot(df.index, df[0])

enter image description here

like image 76
Romain Avatar answered Sep 29 '22 04:09

Romain