Home > Backend Development > Python Tutorial > How Can I Add Custom Text Labels to Data Points in a Matplotlib Scatter Plot?

How Can I Add Custom Text Labels to Data Points in a Matplotlib Scatter Plot?

DDD
Release: 2024-11-28 08:10:11
Original
692 people have browsed it

How Can I Add Custom Text Labels to Data Points in a Matplotlib Scatter Plot?

Customizing Text Labels on Scatter Plot Data Points

When creating a scatter plot, it is often useful to annotate data points with additional information. This can be particularly helpful for distinguishing between points that may be clustered together. One common scenario is the need to display different numbers at each data point, which can be achieved using the annotate() function.

Consider the following dataset:

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 with corresponding numbers annotated at each point:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# Plot scatter points
ax.scatter(x, y)

# Annotate points with corresponding numbers
for i, txt in enumerate(n):
    ax.annotate(txt, (x[i], y[i]))

# Display plot
plt.show()
Copy after login

The annotate() function takes the text to be displayed, followed by the coordinates of the data point. It offers various formatting options, including font size, color, and alignment. You can refer to the Matplotlib documentation for more details.

The above is the detailed content of How Can I Add Custom Text Labels to Data Points in a Matplotlib Scatter Plot?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template