Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating multiple plots in only one axes using a for loop in python

I have a dataframe that I’m trying to plot in a single axes. It has 5 different columns, where the first 4 columns are the y-axis and the 5th column is the x-axis.

I am trying to make a for loop based on the the dataframe’s column name and loop the data and plot them into one figure.

Below is an example where "names" is the variable that contains the dataframe "df"’s column headers.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df = pd.DataFrame(data) # Column heads contains {"A" "B" "C" "D" "X"}
               
names = []
for col in df.columns:
    names.append(col)

del names[-1]

for head in names:
    fig,ax1 = plt.subplots(1)
    x = df["X"]
    y = df[head]
    
    ax1.plot(x, y)

plt.show()

However, this seems to plot multiple graphs in 4 different figures and consequently in 4 separate axes. How could I adjust the code so that it only outputs one figure with a single axes with 4 different lines? Thanks.

>Solution :

Assuming this example:

   y1  y2  y3  y4   x
0   0   4   8  12  16
1   1   5   9  13  17
2   2   6  10  14  18
3   3   7  11  15  19

you could use:

import matplotlib.pyplot as plt
f, axes = plt.subplots(nrows=2, ncols=2)

for i, col in enumerate(df.columns[:-1]):
    ax = axes.flat[i]
    ax.plot(df['x'], df[col])
    ax.set_title(col)

output:

pure matplotlib

only one plot:
df.set_index('x').plot()

or with a loop:

ax = plt.subplot()
for name, series in df.set_index('x').items():
    ax.plot(series, label=name)
ax.legend()

output:

single plot

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading