2

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.

1
  • Please post an actual minimal reproducible example. You're already pretty close, but you can initialize the df and axes. Commented Apr 15, 2022 at 8:15

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

I see, I think I may have worded my question incorrectly. But I would like to have just one plot figure, where there are 4 different colors and 4 different lines in one figure.
@Drew then just set 'x' as index, no need to loop (see update) ;)
NB. in matplotlib a "figure" is an ensembles of "axes". In my first example there is one figure with 4 axes, thus the confusion!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.