Search code examples
pythonmatplotlib

Plot multiple column pairs in one plot


I have columns of data in an excel sheet. The data is paired. I want to plot column 1 and 2 together, 3 and 4 together and so on. In my case I have four columns.

I've tried creating a for loop to go through the data and plot it but I keep getting a separate plots. Anyone know what's wrong here?

    for i in range(0,data.shape[1]):
       if i%2 == 0:
          plt.plot(data.iloc[:,i], data.iloc[:,i+1])
          plt.xlabel('Strain (mm)')
          plt.ylabel('Stress (lbf)')
          plt.show()

Solution

  • If I understand you correctly, you want to generate a single plot using several column combinations. You should create an axis object and then add the data to it.

    import numpy as np
    import pandas as pd
    from matplotlib import pyplot as plt
    
    data = pd.DataFrame({
        'col1': np.linspace(0, 0.2, 100),
        'col2': np.linspace(0, 0.2, 100),
        'col3': np.linspace(0.2, 1, 100),
        'col4': np.linspace(0.2, 1, 100)
    })
    
    fig, ax = plt.subplots()
    
    for i in range(0, data.shape[1]):
       if i%2 == 0:
          ax.plot(data.iloc[:,i], data.iloc[:,i+1])
           
    ax.set_xlabel('Strain (mm)')
    ax.set_ylabel('Stress (lbf)')