0

I am trying to make subplots from multiple columns of a pandas dataframe. Following code is somehow working, but I would like to improve it by moving all the legends to outside of plots (to the right) and add est_fmc variable to each plot.

L = new_df_honeysuckle[["Avg_1h_srf_mc", "Avg_1h_prof_mc", "Avg_10h_fuel_stick", "Avg_100h_debri_mc", "Avg_Daviesia_mc", 
                        "Avg_Euclaypt_mc", "obs_fmc_average", "obs_fmc_max", "est_fmc"]].resample("1M").mean().interpolate().plot(figsize=(10,15), 
                        subplots=True, linewidth = 3, yticks = (0, 50, 100, 150, 200))

plt.legend(loc='center left', markerscale=6, bbox_to_anchor=(1, 0.4))

Any help highly appreciated.

enter image description here

Sher
  • 369
  • 2
  • 19

1 Answers1

2

Since the plotting function of pandas does not allow for fine control, it is easiest to use the subplotting function of mpl and handle it through loop processing.' It was unclear whether you wanted to add the 'est_fmc' line or annotate it, so I added the line. For annotations, see this.

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
import numpy as np
import itertools

columns = ["Avg_1h_srf_mc", "Avg_1h_prof_mc", "Avg_10h_fuel_stick", "Avg_100h_debri_mc", "Avg_Daviesia_mc", "Avg_Euclaypt_mc", "obs_fmc_average", "obs_fmc_max",'est_fmc']

date_rng = pd.date_range('2017-01-01','2020-02-01', freq='1m')

df = pd.DataFrame({'date':pd.to_datetime(date_rng)})

for col in columns:
    tmp = np.random.randint(0,200,(37,))
    df = pd.concat([df, pd.Series(tmp, name=col, index=df.index)], axis=1)
    
fig, axs = plt.subplots(len(cols[:-1]), 1, figsize=(10,15), sharex=True)
fig.subplots_adjust(hspace=0.5)
colors = mcolors.TABLEAU_COLORS

for i,(col,cname) in enumerate(zip(columns[:-1], itertools.islice(colors.keys(),9))):
    axs[i].plot(df['date'], df[col], label=col, color=cname)
    axs[i].plot(df['date'], df['est_fmc'], label='est_fmc', color='tab:olive')
    axs[i].set_yticks([0, 50, 100, 150, 200])
    axs[i].grid()
    axs[i].legend(loc='upper left', bbox_to_anchor=(1.02, 1.0))

plt.show()

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32
  • thanks a lot @r-beginners. How do you assign custom colors into for each line? – Sher May 14 '21 at 08:39
  • There are several ways to do [this answer(middle position)](https://stackoverflow.com/questions/16834861/create-own-colormap-using-matplotlib-and-plot-color-scale), but here is an example of using a colormap, specifying any color. – r-beginners May 14 '21 at 10:19