For loop scatter plot python

You could do something like this:

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

# Create dummy dataframe, or load your own with pd.read_csv()

columns = ["sex", "age", "BMI", "smoke", "type"]
data = pd.DataFrame(np.array([[1,0,0,1,0], [23,16,94,18,24], [32, 26, 28, 23, 19], [0,1,1,1,0], [1,2,2,2,1]]).T, columns=columns)


x_col = "sex"
y_columns = ["age", "BMI", "smoke"]


for y_col in y_columns:

    figure = plt.figure
    ax = plt.gca()
    ax.scatter(data[x_col], data[y_col])
    ax.set_xlabel(x_col)
    ax.set_ylabel(y_col)
    ax.set_title("{} vs {}".format(x_col, y_col))

    plt.legend()
    plt.show()

Basically, if you have your dataset saved as a .csv file, you can load it with pandas using pd.read_csv(), and use the column names as keys to access the corresponding rows, and iterate on that (here I created a dummy dataframe just for the sake of it).

Regarding the linear regression part, you should check out the scikit-learn library. It has a lot of regression models for many different tasks like regression, classification and clustering

$\begingroup$

I want to create scatterplot of target variable with all the other variables in dataframe. Just like we create pairplot but as pairplot with large number of variables will take lot of time and computing memory, it is required to draw scatter plot containing all the variables with target variable. So tried implementing it in for loop, but only last one got rendered properly.

count=1
for i in df.columns:
    plt.subplot(n,1,count)
    plt.figure(figsize=[5,5])
    sns.scatterplot(df["cnt"],df[i])
    count+=1

output: only last plot is rendered properly

For loop scatter plot python

asked Nov 2, 2020 at 14:54

For loop scatter plot python

$\endgroup$

$\begingroup$

Just get rid of the plt.figure(figsize=[5,5])

count=1
for i in df.columns:
    plt.subplot(n,1,count)
    sns.scatterplot(df["cnt"],df[i])
    count+=1

plt.show()

or use this to make it more beautier (Adjust the first two parameters of subplot function, i.e. 3, 2, to if you have more columns. First parameter specifies the number of rows for subplots in the plot, and second parameter specifies number of columns)

count=1
plt.subplots(figsize=(10, 8))
for i in df.columns:
    plt.subplot(3,2,count)
    sns.scatterplot(df["cnt"],df[i])
    count+=1

plt.show()

answered Nov 2, 2020 at 17:52

For loop scatter plot python

$\endgroup$

In this Python Matplotlib tutorial, we will discuss the Matplotlib update plot in loop. Here we will cover different examples related to update plot in loop using matplotlib. And we will also cover the following topics:

  • Matplotlib update plot in loop
  • Matplotlib update plot in jupyter
  • Matplotlib update scatter plot in loop
  • Matplotlib update plot in while loop
  • Matplotlib update plot in for loop

To update the plot on every iteration during the loop, we can use matplotlib. We constantly update the variables to be plotted by iterating in a loop and then plotting the changed values in Matplotlib to plot data in real-time or make an animation.

We use a variety of approaches to visualize the updated plot in real-time through animation, such as:

  • canvas.draw() with canvas_flush_events() function
  • FuncAnimation() function

canvas.draw with canvas_flush_events() function

By updating the variables, we can update the plot in the loop and then display updates through animations using canvas.draw() function.

Example:

# Interactive Mode

%matplotlib notebook

# Import Library


import numpy as np
import time
import matplotlib.pyplot as plt

# Create subplots

figure, ax = plt.subplots(figsize=(4,5))

# Data Coordinates

x = np.linspace(0, 20, 80)
y = np.sin(x)

# GUI

plt.ion()

#  Plot

plot1, = ax.plot(x, y)

# Labels

plt.xlabel("X-Axis",fontsize=18)
plt.ylabel("Y-Axis",fontsize=18)

for value in range(150):
    update_y_value = np.sin(x-2.5*value)
    
    plot1.set_xdata(x)
    plot1.set_ydata(update_y_value)
    
    figure.canvas.draw()
    figure.canvas.flush_events()
    time.sleep(0.1)


# Display

plt.show()

Explanation:

  • Firstly, turn on the interactive mode.
  • Next, import libraries such as numpy, time, and matplotlib.pyplot.
  • Create subplot by using subplots() function.
  • Next define data coordinate, using linespace() and sin() function.
  • To update the plot with x and y values, we use ion() function.
  • To plot the line, we use plot() function.
  • To define labels, we use xlabel() and ylabel() function.
  • Then we update the variables x and y with set_xdate() and set_ydata() function.
  • To display updates, we use canvas.draw() function.
  • To get the new figure, we use canvas.flush_event()

Output:

Matplotlib update plot in loop example-1

FuncAnimation() function

Here we’ll learn to update a plot by updating the variables and displaying them by using the animation function.

The following is the syntax:

matplotlib.animation.FuncAnimation(fig, func, frames=None, 
                                   init_func=None, 
                                   fargs=None, 
                                   save_count=None, * ,    
                                   cache_frame_data=True, 
                                   **kwargs)

Example:

# Import Library

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# Create figure and subplot

figure, ax = plt.subplots(figsize=(4,3))

x = []
y = []

# Plot

plot_1, = ax.plot(x, y)
plt.axis([0, 30, -2, 2])

# Animation Function

def animate_plot (i):
    x = np.linspace(0, 30, 100)
    y = np.tan(6 * (x - 0.3 * i))
    plot_1.set_data(x, y)
    return plot_1,

# Animated Function

ani = FuncAnimation(figure,
                    animate_plot,
                    frames=3,
                    interval=100)

# Save as gif

ani.save('animation.gif', fps=10)

# Display

plt.show()

Explanation:

  • Import libraries such as numpy, matplotlib.pyplot, and animation.
  • Next, we use the figure() function to plot will be updated.
  • To plot the line chart, we use the plot() function.
  • To set the axes, we use the axis() function.
  • Define data coordinates, using linespace() and tan() function of numpy.
  • The function to be called at each frame is animate_plot. Its first argument is derived from the next value frames.
  • The FuncAnimation() function is used to animate the plot.
  • To save the plot in gif plot, we use save() function.

Matplotlib update plot in loop example-2

Also, check: Matplotlib Pie Chart Tutorial

Matplotlib update plot in Jupyter

We’ll learn to update the plot in Jupyter. For this, we have to import display and clear_output. Now we have two different ways to update our plots, let’s see one by one:

  • clear axes befor plotting
  • without clearing axes before plotting

Clear axes befor plotting

Here we update the plot in Jupyter, and in this approach, we clear the axes before plotting the graph.

Example:

# Import Libraries

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, clear_output

# Create figure and subplot

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1) 

# Define and update plot

for i in range(20):
    x = np.linspace(0, i, 100);
    y = np.cos(x) 
    ax.set_xlim(0, i)    
    ax.cla()
    ax.plot(x, y)
    display(fig)    
    clear_output(wait = True)
    plt.pause(0.1)
  • Firstly, import numpy, matplotlib.pyplot, display and clear_output libraries.
  • After this, we create figure and subplot, using figure() and add_subplot() functions.
  • Next, define data coordinates, using linspace() and cos() function.
  • To set the limits, we use set_xlim() function.
  • To plot the graph, we use plot() function.
  • To clear the screen, we use cla() function.
  • To display the figure, display() function.
  • To clear the output, we use clear_output() function.
  • To pause the execution of code, we use pause() function.

Output:

matplotlib update plot in jupyter example-1

Without clearing axes before plotting

Here we update the plot in Jupyter, and in this approach, we plot the graph without clearing the axes before the graph.

Example:

# Import Libraries

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, clear_output

# Create figure and subplot

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1) 

# Define and update plot

for i in range(100):
    ax.set_xlim(0, 50)
    ax.plot(i, 2, marker='o')
    display(fig)    
    clear_output(wait = True)
    plt.pause(0.2)
  • Import numpy, matplotlib.pyplot, display and clear_output libraries.
  • After this, we create figure and subplot, using figure() and add_subplot() functions.
  • Next, define data coordinates, using linspace() and cos() function.
  • To set the limits, we use set_xlim() function.
  • To plot the graph, we use plot() function.
  • To display the figure, display() function.To clear the output, we use clear_output() function.
  • To pause the execution of code, we use pause() function.

Output:

matplotlib update plot in jupyter example-2

Read: Matplotlib multiple bar chart

Matplotlib update scatter plot in loop

Here we’ll learn to update the scatter plots. For this, we can update the values of x and y and add scatter points in each iteration.

Example:

# Import Libraries


import numpy as np

import matplotlib.pyplot as plt

# Create Scatter Plot


x=0
for i in range(40):

    x=np.sin(i)
    y = np.cos(30*x-5)

    plt.scatter(x, y)

    plt.title("Scatter Plot")

    plt.xlabel("X-Axis")
    plt.ylabel("Y-Axis")

    plt.pause(0.2)

# Display

plt.show()
  • Firstly, we import libraries such as numpy and matplotlib.
  • Next, we create a scatter plot using range() and scatter() function.
  • To add a title, we use the title() function.
  • To add axes labels, we use the xlable() and ylabel() functions.
  • To pause the execution, we use the pause() function.
  • To display the graph, we use the show() function.

Output:

Matplotlib update scattter plot in loop example

Read: Matplotlib 3D scatter

Matplotlib update plot in while loop

Here we’ll see an example where we create a plot and update its x and y coordinates at each iteration by using the while loop.

The syntax is given below:

while test_expression:
    Body of while

Example:

# Import Libraries

import matplotlib.pyplot as plt
import numpy as np

# GUI

plt.ion()

# Create figure

fig=plt.figure()

# Define Data

data=0
x=list()
y=list()

# While loop

while data <50:
    new_y=np.random.random();
    x.append(data);
    y.append(new_y);
    plt.scatter(data,new_y,marker='*');
    data+=1;
    plt.show()
    plt.pause(0.1) 

Output:

Matplotlib update plot in while loop example

Read: Matplotlib plot bar chart

Matplotlib update plot in for loop

Here we’ll see an example where we create a plot and update its x and y coordinates at each iteration by using for loop.

The syntax is given below:

for val in sequence:
    loop body

Example:

# Import Library
  
import matplotlib.pyplot as plt
import numpy as np

# For loop

for n in range(5):
    x = np.linspace(0,10)
    y = np.sin( x+n )
    plt.scatter( x, y )
    plt.pause(0.5) 

# Display


plt.show()
  • Import matplotlib.pyplot and numpy libraries.
  • Next, use range(), linespace(), and sin() functions to define data coordinates.
  • To plot the graph, we use the scatter() function.

Output:

Matplotlib update plot in for loop example

You may also like to read the following tutorials on Matplotlib.

  • Matplotlib default figure size
  • Matplotlib time series plot
  • Matplotlib savefig blank image
  • Matplotlib bar chart labels
  • Matplotlib set y axis range
  • Matplotlib plot error bars
  • Matplotlib xlim – Complete Guide
  • module ‘matplotlib’ has no attribute ‘plot’

So, in this Python tutorial, we have discussed the “Matplotlib update plot in loop” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Matplotlib update plot in loop
  • Matplotlib update plot in jupyter
  • Matplotlib update scatter plot in loop
  • Matplotlib update plot in while loop
  • Matplotlib update plot in for loop

For loop scatter plot python

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

How do you plot multiple scatter plots in for loop in Python?

for loop for multiple scatter plots.
count=1..
plt. subplots(figsize=(10, 8)).
for i in df. columns:.
plt. subplot(3,2,count).
sns. scatterplot(df["cnt"],df[i]).
count+=1..
plt. show().

How do you dynamically plot in Python?

To dynamically update plot in Python matplotlib, we can call draw after we updated the plot data. to define the update_line function. In it, we call set_xdata to set the data form the x-axis. And we call set_ydata to do the same for the y-axis.

Can you draw scatter plot using python?

scatter() in Python. Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. It is used for plotting various plots in Python like scatter plot, bar charts, pie charts, line plots, histograms, 3-D plots and many more.

How do you update a loop in Matplotlib?

Matplotlib update plot in loop..
Firstly, turn on the interactive mode..
Next, import libraries such as numpy, time, and matplotlib. ... .
Create subplot by using subplots() function..
Next define data coordinate, using linespace() and sin() function..
To update the plot with x and y values, we use ion() function..