Stephanie Yarborough
Stephanie Yarborough

Reputation: 31

Iterating through columns for separate plots in Python

I am extremely new to coding, so I appreciate any help I can get. I have a large data file that I want to create multiple plots for where the first column is the x axis for all of them. The code would ideally then iterate through all the columns with each respectively being the new y axis. I included my code for the individual plots, but want to create a loop to do it for all the columns.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

X = df[:,0]
col_1= df[:,1]
plt.plot(X,col_1)
plt.show()

col_2= df[:,2]
plt.plot(X,col_2)
plt.show()

Upvotes: 3

Views: 10873

Answers (2)

bear24rw
bear24rw

Reputation: 4617

You could loop through each column plotting it on its own subplot like so:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(df.shape[1]-1, sharex=True)
for i in range(df.shape[1]-1):
    ax[i].plot(df[:,0], df[:,i+1])

plt.show()

edit

I just realized your example was displaying 1 plot at a time. You could accomplish that like this:

import matplotlib.pyplot as plt

for i in range(df.shape[1]-1):
    plt.plot(df[:,0], df[:,i+1])
    plt.show()
    plt.close()

Upvotes: 1

Ted Petrou
Ted Petrou

Reputation: 61967

Pandas will iterate over all the columns for you. Simply place the x column in the index and then just make a call to plot with your dataframe. Pandas uses the index as the x-axis There is no need to directly use matplotlib. Here is some fake data with a plot:

df = pd.DataFrame(np.random.rand(10,5), columns=['x', 'y1', 'y2', 'y3', 'y4'])
df = df.sort_values('x')

          x        y1        y2        y3        y4
9  0.262202  0.417279  0.075722  0.547804  0.599150
5  0.314894  0.611873  0.880390  0.282140  0.513770
8  0.406541  0.933734  0.879495  0.500626  0.527526
2  0.407636  0.550611  0.646449  0.635693  0.807088
1  0.437580  0.194937  0.501611  0.949575  0.409130
4  0.497347  0.443345  0.658259  0.457635  0.851847
3  0.500726  0.569175  0.304910  0.151071  0.678991
6  0.547433  0.512125  0.539995  0.701858  0.358552
0  0.783461  0.649381  0.320577  0.107062  0.840443
7  0.793702  0.951807  0.938635  0.526010  0.098321

df.set_index('x').plot(subplots=True)

enter image description here

Upvotes: 4

Related Questions