plot multiple columns in a different grid in same plot in different colors

Viewed 147

I have a dataframe with three columns

data = np.array([[0,'Time',27.390000],
                [0,'Score',0.027585],
                [1,'Time',47.390000],
                [1,'Score',0.23776],
                [2,'Time',65.390000],
                [2,'Score',0.44776]])
data = pd.DataFrame(data)
data.columns = ['Rounds','Metrics','WA_All_par_1']
data["WA_All_par_1"] = pd.to_numeric(data["WA_All_par_1"])

data
        Rounds  Metrics WA_All_par_1
     0  0       Time    27.390000
     1  0       Score   0.027585
     2  1       Time    47.390000
     3  1       Score   0.237760
     4  2       Time    65.390000
     5  2       Score   0.447760

I pivot the dataframe "Metrics" column

data= data.pivot(index='Rounds', columns='Metrics', values='WA_All_par_1').reset_index().rename_axis(columns=None)
data.dropna(how='all')
data.head()


    Rounds  Score       Time
 0  0       0.027585    27.39
 1  1       0.237760    47.39
 2  2       0.447760    65.39

data.set_index('Rounds').plot(figsize=(7,6), grid=True)

enter image description here

I want to plot the two columns Time and Score in separate grid in same plot

1 Answers

Based on this example you can add a second y axis with a different scale

ax1 = plt.gca()
ax1.plot(data['Rounds'], data['Score'], color='red')
ax1.set_xlabel('Rounds')
ax1.set_ylabel("Score")
ax1.set_ylim([0.,0.5])
ax2 = ax1.twinx()
ax2.plot(data['Rounds'], data['Time'], color='blue')
ax2.set_ylabel("Time")
ax2.set_ylim([0, 70])
plt.show()

two scales

Edit: as alternative you can use subplots. When creating the subplots use sharex=True sharey=False so that all subplots will use the same scale on the x axis but can use different scales for the y axis.

fig, axs = plt.subplots(2, sharex=True, sharey=False)

axs[0].plot(data['Rounds'], data['Score'], color='red')
axs[0].set_xlabel('Rounds')
axs[0].set_ylabel("Score")
axs[0].set_ylim([0.,0.5])

axs[1].plot(data['Rounds'], data['Time'], color='blue')
axs[1].set_xlabel('Rounds')
axs[1].set_ylabel("Time")
axs[1].set_ylim([0.,70])

plt.show()

subplots

Related