0

Hi I have a dataframe liek this:

data1 = {"x": [10,20,30,40,50], 
         "y": [0.01,0.02,0.03,0.04,0.05],
         "z": [0.11,0.12,0.13,0.14,0.15],
         "q": [0.21,0.22,0.23,0.24,0.25],}
df1 = pd.DataFrame (data1, columns = ['x','y','z','q'])

And I want to create a plot of x against y, against z, and against q as subplots on a plot.

I have done this, but they are on the same plot

import matplotlib.pyplot as plt

plt.plot(df1['y'], df1['x'])
plt.plot(df1['z'], df1['x'])
plt.plot(df1['q'], df1['x'])

Additonally is there a way I can add a label for eahc line ?

1 Answers1

2

To add legend to each line, you could assgin each line with a label, then call plt.legend() to draw the legend.

import pandas as pd
import matplotlib.pyplot as plt

data1 = {"x": [10,20,30,40,50], 
         "y": [0.01,0.02,0.03,0.04,0.05],
         "z": [0.11,0.12,0.13,0.14,0.15],
         "q": [0.21,0.22,0.23,0.24,0.25],}
df1 = pd.DataFrame (data1, columns = ['x','y','z','q'])

plt.plot(df1['y'], df1['x'], label='y')
plt.plot(df1['z'], df1['x'], label='z')
plt.plot(df1['q'], df1['x'], label='q')

plt.legend()

plt.show()

enter image description here

To plot them on different subplots, you could create mxn subplots by defining the nrows and ncols parameters in plt.subplots(). Then plot data on each axes object.

import pandas as pd
import matplotlib.pyplot as plt

data1 = {"x": [10,20,30,40,50], 
         "y": [0.01,0.02,0.03,0.04,0.05],
         "z": [0.11,0.12,0.13,0.14,0.15],
         "q": [0.21,0.22,0.23,0.24,0.25],}
df1 = pd.DataFrame (data1, columns = ['x','y','z','q'])

figure, axs = plt.subplots(nrows=1, ncols=3, figsize=(8, 4))

axs[0].plot(df1['y'], df1['x'], label='y')
axs[1].plot(df1['z'], df1['x'], label='z')
axs[2].plot(df1['q'], df1['x'], label='q')

axs[0].set_title('x against y')
axs[1].set_title('x against z')
axs[2].set_title('x against q')

plt.show()

enter image description here

Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52