Home >Backend Development >Python Tutorial >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]
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()
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:
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!