
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to overplot a line on a scatter plot in Python?
First, we can create a scatter for different data points using the scatter method, and then, we can plot the lines using the plot method.
Steps
Create a new figure, or activate an existing figure with figure size(4, 3), using figure() method.
Add an axis to the current figure and make it the current axes, create x using plt.axes().
Draw scatter points using scatter() method.
Draw line using ax.plot() method.
Set the X-axis label using plt.xlabel() method.
Set the Y-axis label using plt.ylabel() method.
To show the plot, use plt.show() method.
Example
import random import matplotlib.pyplot as plt plt.figure(figsize=(4, 3)) ax = plt.axes() ax.scatter([random.randint(1, 1000) % 50 for i in range(100)], [random.randint(1, 1000) % 50 for i in range(100)]) ax.plot([1, 2, 4, 50], [1, 2, 4, 50]) ax.set_xlabel('x') ax.set_ylabel('y') plt.show()
Output
- Related Articles
- Adding a line to a scatter plot using Python's Matplotlib
- How to make a 3D scatter plot in Python?
- How to draw an average line for a scatter plot in MatPlotLib?
- How to make a scatter plot for clustering in Python?
- How to plot additional points on the top of a scatter plot in Matplotlib?
- Connecting two points on a 3D scatter plot in Python and Matplotlib
- How to animate a scatter plot in Matplotlib?
- How to plot scatter masked points and add a line demarking masked regions in Matplotlib?
- How can Seaborn library be used to display a Scatter Plot in Python?
- Python Plotly – How to simultaneously apply color/shape/size in a Scatter Plot?
- Python - Draw a Scatter Plot for a Pandas DataFrame
- Create a Scatter Plot with SeaBorn – Python Pandas
- Controlling the alpha value on a 3D scatter plot using Python and Matplotlib
- Plot a multicolored line based on a condition in Python Matplotlib
- Python Plotly – How to manually set the color of points in a scatter plot?

Advertisements