Home > Backend Development > Python Tutorial > How Can I Create a Scatter Plot with Annotations in Python?

How Can I Create a Scatter Plot with Annotations in Python?

Barbara Streisand
Release: 2024-11-23 00:50:12
Original
904 people have browsed it

How Can I Create a Scatter Plot with Annotations in Python?

Scatter Plot with Annotations

Creating a scatter plot with different text annotations at each data point can enhance the visualization and provide insights into the relationships within the data. Here's a Python solution to this challenge:

Consider 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

To create a scatter plot and annotate each data point with the corresponding number in n, follow these steps:

import matplotlib.pyplot as plt

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

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

The annotate() function allows you to add text annotations to the scatter plot. It takes the text to be annotated and the coordinates of the point where the annotation should be placed. In this case, we iterate over the elements in n and place the annotations at the corresponding data points.

The annotate() function provides various formatting options, such as font properties, colors, and positioning. For example, to change the font size of the annotations, you can use the fontsize parameter:

for i, txt in enumerate(n):
    ax.annotate(txt, (x[i], y[i]), fontsize=12)
Copy after login

By providing different text annotations at each data point, you can add context and meaning to your scatter plot, making it easier to interpret and draw conclusions from the data.

The above is the detailed content of How Can I Create a Scatter Plot with Annotations in Python?. For more information, please follow other related articles on the PHP Chinese website!

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