Home > Backend Development > Python Tutorial > How to Annotate a Scatter Plot with Individual Data Point Text Values?

How to Annotate a Scatter Plot with Individual Data Point Text Values?

Susan Sarandon
Release: 2024-12-02 08:18:12
Original
725 people have browsed it

How to Annotate a Scatter Plot with Individual Data Point Text Values?

Scatter Plot with Individual Data Point Text Annotations

Question:

How can I create a scatter plot and annotate each data point with a specific text value from a given list?

Example:

Given the following data:

y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
x = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]
Copy after login

Can I generate a scatter plot of y vs x and annotate each point with the corresponding value from n?

Answer:

Since there is no direct plotting method that supports annotating data points with text from a list, an alternative approach is to use the annotate() method:

import matplotlib.pyplot as plt

x = [0.15, 0.3, 0.45, 0.6, 0.75]
y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
n = [58, 651, 393, 203, 123]

fig, ax = plt.subplots()
ax.scatter(x, y)

for i, txt in enumerate(n):
    ax.annotate(txt, (x[i], y[i]))

plt.show()
Copy after login

This code creates a scatter plot and iterates over the text values in the n list, annotating each data point with the corresponding value.

Formatting Options:

Matplotlib provides various formatting options for annotations, including:

  • Text color and size
  • Background color and shape
  • Arrow style and position
  • Alignment and rotation

For more information on formatting options, refer to the Matplotlib documentation:

[https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.annotate.html](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.annotate.html)

The above is the detailed content of How to Annotate a Scatter Plot with Individual Data Point Text Values?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template