Plot two dataframes with same formats on same graph but only one graph per column

Question:

I have two dataframes, df_iter_actuals and df_iter_preds that look like this:

cohort  FGCI 0.0 2017   FGCI 1.0 2020   FGCI 1.0 2021
Month_Next          
2022-04-01  1.207528    10.381440   4.332759
2022-05-01  1.529364    1.649636    5.007991
2022-06-01  21.715032   7.491215    6.096792
2022-07-01  0.958635    12.460808   5.759696
2022-08-01  25.637608   0.961132    4.635855
2022-09-01  0.997071    0.721632    3.799172
2022-10-01  27.006847   0.811228    3.586541
cohort  FGCI 0.0 2017   FGCI 1.0 2020   FGCI 1.0 2021
Month_Next          
2022-04-01  16.804628   5.143954    3.296097
2022-05-01  16.804628   5.143954    3.193598
2022-06-01  16.804628   5.143954    3.066248
2022-07-01  16.804628   5.143954    2.907984
2022-08-01  16.804628   5.143954    2.711235
2022-09-01  16.804628   5.143954    2.466544
2022-10-01  16.804628   5.143954    2.162079

One is the actual values and the other is the predicted values for a certain time series data set. I’d like to plot the shared columns between the two dataframes on a single plot, but creating a new plot for each column. For example, I’d like the data for FGCI 0.0 2017 to be shown on the same plot as line graphs for both dfs, and then for the next plot showing the data for FGCI 1.0 2020. I was able to accomplish this with just one dataframe with

for i in df_iter_actuals.columns:
    plt.figure(figsize = (10,8))
    plt.plot(df_iter[i])
    plt.title(f'Pct Error of CPR Predictions for {i}')

But I don’t know how to do it with two dataframes.

Asked By: hulio_entredas

||

Answers:

# Create figure and axes
fig, ax = plt.subplots(figsize=(10, 8))

# Iterate over columns in dataframes
for col in df_iter_actuals.columns:
    # Use the `df.plot()` function to plot the column from each dataframe
    df_iter_actuals[col].plot(ax=ax, label="Actual")
    df_iter_preds[col].plot(ax=ax, label="Predicted")

    # Set the title of the plot to the column name to whatever you need
    ax.set_title(f"Pct Error of CPR Predictions for {col}")
    
    # Show the plot and legend
    ax.legend()
    plt.show()

Just iterate over the columns of your two dataframes and then use the df.plot() function to plot each column from both dataframes on the same graph figure!

Answered By: J. M. Arnold

Since the format/column name is the same for both df, you can just call them :

for i in df_iter_actuals.columns:
    plt.figure(figsize = (10,8))
    plt.plot(df_iter_actuals[i])
    plt.plot(df_iter_preds[i])
    plt.title(f'Pct Error of CPR Predictions for {i}')
Answered By: Anton B

You can concat and use groupby.plot:

(pd.concat([df_iter_actuals, df_iter_preds], keys=['actual', 'pred'], axis=1)
   .groupby(level=1, axis=1).plot()
)
Answered By: mozway
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.