How to plot specific column of pandas dataframe?

Viewed 20987

Unfortunately it doesn't work: I have a dataframe named df

This consists of 5 columns and 100 rows.

I want to plot on the x axis column 0 (time) and on the y-axis the corresponding values .

I tried:

figure, ax1 = plt.subplots()
ax1.plot(df.columns[0],df.columns[1],linewidth=0.5,zorder=1, label = "Force1")
ax1.plot(df.columns[0],df.columns[2],linewidth=0.5,zorder=1, label = "Force2")

But this is not working.

I can not directly address the column name - I have only the possibility to use the number of the column (like 1, 2 or number 3).

Thanks for your help!!!

Helmut

1 Answers

You can either use .iloc[] and the column position or pass it through .columns as an argument:

figure, ax1 = plt.subplots()
ax1.plot(df[df.columns[0]],df[df.columns[1]],linewidth=0.5,zorder=1, label = "Force1")
ax1.plot(df[df.columns[0]],df[df.columns[2]],linewidth=0.5,zorder=1, label = "Force2")

Or with .iloc[]:

figure, ax1 = plt.subplots()
ax1.plot(df.iloc[:,0],df.iloc[:,1],linewidth=0.5,zorder=1, label = "Force1")
ax1.plot(df.iloc[:,0],df.iloc[:,2],linewidth=0.5,zorder=1, label = "Force2")

Alternatively define the columns name list and then pass its index (which is the same as the first method):

cols = df.columns
figure, ax1 = plt.subplots()
ax1.plot(df[cols[0]],df[cols[1]],linewidth=0.5,zorder=1, label = "Force1")
ax1.plot(df[cols[0]],df[cols[2]],linewidth=0.5,zorder=1, label = "Force2")
Related