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