how to iterate over pandas rows and create a separate matplotlib plot in python

To iterate over pandas rows and create separate matplotlib plots in Python, you can use a combination of the iterrows() function from pandas and the plot() function from matplotlib.

Here's an example of how you can achieve this:

main.py
import pandas as pd
import matplotlib.pyplot as plt

# Create a sample DataFrame
df = pd.DataFrame({'x': [1, 2, 3, 4, 5], 'y': [10, 20, 30, 40, 50]})

# Iterate over the rows using iterrows()
for index, row in df.iterrows():
    x = row['x']
    y = row['y']
    
    # Create a separate plot for each row
    plt.figure()
    plt.plot(x, y)
    plt.title(f'Plot for Row {index}')
    plt.xlabel('X')
    plt.ylabel('Y')
    plt.show()
436 chars
19 lines

In this example, we create a DataFrame with two columns (x and y). We then iterate over each row using the iterrows() function. Inside the loop, we extract the values of x and y for the current row. We then create a separate plot using plt.figure(), plot the values using plt.plot(), and customize the plot with a title, x-axis label, and y-axis label. Finally, we use plt.show() to display the plot.

Each iteration of the loop will create a new plot with different values for x and y, resulting in separate plots for each row.

related categories

gistlibby LogSnag