ilearn
ilearn

Reputation: 193

How to plot columns of two separate DataFrames in one plot ( subplots representing each column)

I have two DataFrames like below. They are exactly the same in terms of column names and structure. The difference is one dataframe is prediction and one is observed data. I need to plot a figure with subplots where each subplot title is the column names, X-axis is the index values and Y-axis is the values in the table. I need two lines drawn in each graph, 1 from the dataframe with prediction, one with observed. Below is what I have been trying to do but its not working.

      08FB006     08FC001    08FC005        08GD004     08GD005
----------------------------------------------------------------
0   1.005910075 0.988765247 0.00500000  0.984376392 5.099999889
1   1.052696367 1.075232414 0.00535313  1.076066586 5.292135227
2   1.101749034 1.169026145 0.005731682 1.176162168 5.491832766
3   1.153183046 1.270744221 0.006137526 1.285419625 5.699405829
4   1.207119522 1.381030962 0.006572672 1.404662066 5.915181534
5   1.263686077 1.500580632 0.007039282 1.534784937 6.139501445
6   1.323017192 1.630141078 0.007539681 1.676762214 6.372722261
7   1.38525461  1.770517606 0.008076372 1.831653101 6.615216537
8   1.450547748 1.922577115 0.008652045 2.000609283 6.867373442
9   1.519054146 2.087252499 0.009269598 2.184882781 7.129599561
10  1.590939931 2.265547339 0.009932148 2.385834436 7.402319731

The sample code, I have 81 stations/columns

import matplotlib.pyplot as plt
%matplotlib inline

fig, axes = plt.subplots(nrows=81, ncols=1)

newdf1.plot(ax=axes[0,0])
newdf1_pred.plot(ax=axes[0,1])

Upvotes: 0

Views: 913

Answers (1)

E. Chris Lynch
E. Chris Lynch

Reputation: 26

I set up a dummy dataframe to help visualize what I did.

import pandas as pd
import numpy as np

obs = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
pred = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

Plotting two dataframes on the same plot is no different than plotting two columns. You just have to include them on the same axis. Here is how I did it:

import matplotlib.pyplot as plt
%matplotlib inline

fig, axes = plt.subplots(figsize=(5,7), nrows=4, ncols=1)
for col in range(len(obs.columns)): # loop over the number of columns to plot
    obs.iloc[col].plot(ax=axes[col], label='observed') # plot observed data
    pred.iloc[col].plot(ax=axes[col], label='predicted') # plot predicted data
    axes[col].legend(loc='upper right') # legends to know which is which
    axes[col].set_title(obs.columns[col]) # titles to know which column/variable
plt.tight_layout() # just to make it easier to read the plots

Here was my output:

enter image description here

I hope this helps.

Upvotes: 1

Related Questions