Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot multiple plots using for loop

a=pd.DataFrame({'length':[20,10,30,40,50],
                'width':[5,10,15,20,25],
                'height':[7,14,21,28,35]})

for i,feature in enumerate(a,1):
    sns.regplot(x = feature,y= 'height',data = a)
    print("{} plotting {} ".format(i,feature))

I want to plot 3 different plots with three different columns i.e 'length','width' and 'height' on x-axis and 'height' on y-axis in each one of them .
This is the code i wrote but it overlays 3 different plots over one another.I intend to plot 3 different plots.

like image 505
Bhagwinder Avatar asked Sep 20 '25 12:09

Bhagwinder


1 Answers

It depends on what you want to do. It you want several individual plots, you can create a new figure for each dataset:

import matplotlib.pyplot as plt
for i, feature in enumerate(a, 1):
    plt.figure()  # forces a new figure
    sns.regplot(data=a, x=feature, y='height')
    print("{} plotting {} ".format(i,feature))

Alternatively, you can draw them all on the same figure, but in different subplots. I.E next to each other:

import matplotlib.pyplot as plt
# create a figure with 3 subplots
fig, axes = plt.subplots(1, a.shape[1])
for i, (feature, ax) in enumerate(zip(a, axes), 1):
    sns.regplot(data=a, x=feature, y='height', ax=ax)
    print("{} plotting {} ".format(i,feature))

3 plots next to each other

plt.subplots has several options that allow you to align the plots the way you like. check the docs for more on that!

like image 164
danijoo Avatar answered Sep 23 '25 03:09

danijoo