0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Create Scatter Plot in Matplotlib: Simple Guide

To create a scatter plot in matplotlib, use the plt.scatter(x, y) function where x and y are lists or arrays of data points. Then call plt.show() to display the plot.
๐Ÿ“

Syntax

The basic syntax for creating a scatter plot in matplotlib is:

  • plt.scatter(x, y): Plots points with coordinates from x and y.
  • x: List or array of x-axis values.
  • y: List or array of y-axis values.
  • plt.show(): Displays the plot window.
python
import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [4, 5, 6]

plt.scatter(x, y)
plt.show()
๐Ÿ’ป

Example

This example shows how to create a scatter plot with simple data points for x and y. It plots the points and displays the graph.

python
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [5, 7, 4, 6, 8]

plt.scatter(x, y)
plt.title('Simple Scatter Plot')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.show()
Output
A scatter plot window showing 5 points scattered with x values 1 to 5 and y values 5,7,4,6,8 labeled with title and axis labels.
โš ๏ธ

Common Pitfalls

Common mistakes when creating scatter plots include:

  • Passing x and y of different lengths causes errors.
  • Forgetting to call plt.show() means the plot won't display.
  • Using plt.plot() instead of plt.scatter() creates line plots, not scatter plots.
python
import matplotlib.pyplot as plt

# Wrong: different lengths
x = [1, 2, 3]
y = [4, 5]
# plt.scatter(x, y)  # This will raise an error

# Correct:
x = [1, 2, 3]
y = [4, 5, 6]
plt.scatter(x, y)
plt.show()
๐Ÿ“Š

Quick Reference

Remember these tips for scatter plots in matplotlib:

  • Use plt.scatter(x, y) for scatter plots.
  • Ensure x and y have the same length.
  • Add labels and titles for clarity.
  • Call plt.show() to display the plot.
โœ…

Key Takeaways

Use plt.scatter(x, y) to create scatter plots with matplotlib.
Make sure x and y data lists have the same length to avoid errors.
Always call plt.show() to display your plot window.
Add titles and axis labels to make your plot easy to understand.
Avoid using plt.plot() when you want a scatter plot.