Matplotlib 简明教程
Matplotlib - Annotations
在 Matplotlib 库中,注释是指在绘图中的特定位置添加文本或标记的能力,以提供其他信息或突出显示特定功能。注释允许用户标记数据点并指示趋势或向绘图的不同部分添加描述。
In Matplotlib library annotations refer to the capability of adding text or markers to specific locations on a plot to provide additional information or highlight particular features. Annotations allow users to label data points and indicate trends or add descriptions to different parts of a plot.
Key Aspects of Annotations in Matplotlib
以下是 matplotlib 库中注释的关键方面。
The following are the key aspects of annotations in matplotlib library.
Text Annotations
数据可视化中的文本注释用于向绘图中的特定点、区域或特征添加说明性或描述性文本。注释有助于突出显示重要信息、提供上下文或解释可视化数据中的趋势和模式。
Text annotations in data visualization are used to add explanatory or descriptive text to specific points, regions, or features within a plot. Annotations help in highlighting important information, providing context, or explaining trends and patterns within the visualized data.
Marker Annotations
数据可视化中的标记注释通常涉及在绘图中感兴趣的特定点上放置标记或符号,以突出显示或提供有关这些点的其他信息。这些注释可以是文本性的或图形性的,通常用于引起人们对重要的数据点、峰值、波谷、异常值或可视表示中的任何关键信息的注意。
Marker annotations in data visualization typically involve placing markers or symbols on specific points of interest within a plot to highlight or provide additional information about those points. These annotations can be textual or graphical and are commonly used to draw attention to significant data points, peaks, valleys, outliers or any crucial information in a visual representation.
Callouts
数据可视化中的旁注是指一种特殊的注释类型,它使用箭头、线条或文本等视觉元素来引起对绘图中某一特定区域或特征的注意。它们通常用于提供有关特定数据点或感兴趣区域的附加上下文或解释。
Callouts in data visualization refer to a specific type of annotation that uses visual elements like arrows, lines, or text to draw attention to a particular area or feature within a plot. They are often used to provide additional context or explanations about specific data points or regions of interest.
Matplotlib 库中的 plt.annotate() 函数用于向绘图添加注释。它允许我们在绘图上放置文本注释,并带可选箭头,指向绘图上的特定数据点。
The plt.annotate() function in Matplotlib library is used to add an annotation to a plot. It allows us to place a text annotation with optional arrows pointing to specific data points on the plot.
Syntax
以下是 plt.annotate() 函数的语法。
The following is the syntax for the plt.annotate() function.
plt.annotate(text, xy, xytext=None, xycoords='data', textcoords='data', arrowprops=None, annotation_clip=None, kwargs)
其中,
Where,
-
text (str) − The text of the annotation.
-
xy (tuple or array) − The point (x, y) to annotate.
-
xytext (tuple or array, optional) − The position (x, y) to place the text. If None defaults to
xy
. -
xycoords (str, Artist, or Transform, optional) − The coordinate system that
xy
is given in. Default is 'data'. -
textcoords (str, Artist, or Transform, optional) − The coordinate system that
xytext
is given in. Default is 'data'. -
arrowprops (dict, optional) − A dictionary of arrow properties. If not None an arrow is drawn from the annotation to the text.
-
annotation_clip (bool or None, optional) − If True the text will only be drawn when the annotation point is within the axes. If None it will take the value from rcParams["text.clip"].
-
kwargs (optional) − Additional keyword arguments that are passed to Text.
Adding the annotation to the plot
在此示例中,我们使用 plt.annotate() 函数在绘图中点 (3, 5) 添加包含文本 'Peak' 的注释。
In this example we are using the plt.annotate() function to add an annotation with the text 'Peak' at the point (3, 5) on the plot.
import matplotlib.pyplot as plt
# Plotting data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y, marker='o', linestyle='-', color='blue')
# Adding annotation
plt.annotate('Peak', xy=(3, 5), xytext=(3.5, 6), arrowprops=dict(facecolor='black', arrowstyle='->'), fontsize=10)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Annotated Plot')
plt.grid(True)
plt.show()
以下是使用 ‘plt.annotations’ 函数将注释添加到图像的另一个示例。
Here this is another example of using the ‘plt.annotations’ function for adding the annotation to the image.
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Plotting data
plt.plot(x, y, marker='+', linestyle='-')
# Adding an annotation
plt.annotate('Point of Interest', xy=(3, 6), xytext=(3.5, 7), arrowprops=dict(facecolor='black', arrowstyle='->'))
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Annotated Plot')
plt.grid(True)
plt.show()
Insert statistical annotations (stars or p-values)
在此示例中,我们插入了带有星形 r p 值的统计注释。
In this example we are inserting the statistical annotations as stars r p-values.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-1, 1, 5)
y = np.linspace(-2, 2, 5)
mean_x = np.mean(x)
mean_y = np.mean(y)
fig, ax = plt.subplots()
ax.plot(x, y, linestyle='-.')
ax.annotate('*', (mean_y, mean_y), xytext=(-.50, 1), arrowprops=dict(arrowstyle='-|>'))
fig.autofmt_xdate()
plt.show()
Annotate Matplotlib Scatter Plots
在此示例中,我们向已经绘制好的散点图添加注释。
Here in this example we are adding the annotations to the scatter plot that we have plotted.
# Import necessary libraries
import matplotlib.pyplot as plt
import numpy as np
# Create data points to be plotted
x = np.random.rand(30)
y = np.random.rand(30)
# Define the scatter plot using Matplotlib
fig, ax = plt.subplots()
ax.scatter(x, y)
# Add annotations to specific data points using text or arrow annotations
ax.annotate('Outlier', xy=(0.9, 0.9), xytext=(0.7, 0.7),arrowprops=dict(facecolor='black', shrink=0.05))
ax.annotate('Important point', xy=(0.5, 0.3), xytext=(0.3, 0.1),arrowprops=dict(facecolor='red', shrink=0.05))
ax.annotate('Cluster of points', xy=(0.2, 0.5), xytext=(0.05, 0.7),arrowprops=dict(facecolor='green', shrink=0.05))
# Adjust the annotation formatting as needed
plt.title('Annotated Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Show the scatter plot with annotations
plt.show()
Annotate the points on a scatter plot with automatically placed arrows
在此示例中,我们使用自动放置的箭头对散点图上的点进行注释。
In this example we are annotating the point on a scatter plot with automatically placed arrows.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
xpoints = np.linspace(1, 10, 25)
ypoints = np.random.rand(25)
labels = ["%.2f" % i for i in xpoints]
plt.scatter(xpoints, ypoints, c=xpoints)
for label, x, y in zip(labels, xpoints, ypoints):
plt.annotate(
label,
xy=(x, y), xytext=(-20, 20),
textcoords='offset points', ha='right', va='bottom',
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')
)
plt.show()