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

Time:04-15

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.

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.

CodePudding user response:

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

  • Related