Home >Backend Development >Python Tutorial >How to Annotate Scatter Plot Data Points with Custom Text in Matplotlib?

How to Annotate Scatter Plot Data Points with Custom Text in Matplotlib?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 03:55:09982browse

How to Annotate Scatter Plot Data Points with Custom Text in Matplotlib?

Annotate Scatter Plot Data Points with Custom Text

In data visualization, scatter plots are commonly used to depict the relationship between two variables. To enhance the insights gained from such plots, annotating individual data points with specific information can be valuable. However, annotating each point with different text can pose a challenge.

import matplotlib.pyplot as plt

# Define sample data
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]

# Create the scatter plot
fig, ax = plt.subplots()
ax.scatter(x, y)

Traditional plotting methods don't support annotating points with separate text from lists. Therefore, a workaround is required.

# Iterate over the annotation text and annotate each point
for i, txt in enumerate(n):
    ax.annotate(txt, (x[i], y[i]))

The annotate() function allows for customization of the annotation, including its position and text formatting. By iterating through the list of annotation text, you can assign specific values to each data point.

# Customize the annotation format
ax.annotate(txt, (x[i], y[i]), xytext=(0, 0), textcoords='offset points',
            bbox=dict(boxstyle='round', fc='w'), arrowprops=dict(arrowstyle='->'))

By utilizing annotate() and iterating over the annotation text, you can add customized text to individual data points in a scatter plot, providing valuable insights into the underlying data.

The above is the detailed content of How to Annotate Scatter Plot Data Points with Custom Text in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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