Matplotlib 简明教程

Matplotlib - Findobj Demo

在 Matplotlib 中, findobj 是一种用于在图形中定位和处理图形对象的方法。它的主要目的是提供一种灵活方便的方式来搜索特定 artist 实例并修改它们在绘图中的属性。

In Matplotlib, the findobj is a method used for locating and manipulating graphical objects within a figure. Its primary purpose is to provide a flexible and convenient way to search for specific artist instances and modify their properties within a plot.

此方法在两个接口中均可用,例如 pyplot.findobj()axes.Axes.findobj() (pyplot 和面向对象接口)。Matplotlib 中的所有 Artist 对象都继承了此方法,允许在其层次结构中进行递归搜索。findobj 方法采用一个匹配标准,并且可以将对象本身包含在搜索中(如果需要)。

This method is available in both the interfaces such as pyplot.findobj() and axes.Axes.findobj() (pyplot and Object-oriented interfaces). All Artist objects in Matplotlib inherit this method, allowing for recursive searches within their hierarchy. The findobj method takes a matching criterion and optionally includes the object itself in the search.

在本教程中,我们将探讨 Matplotlib 中 findobj 方法背后的基本概念。

In this tutorial, we will explore the fundamental concepts behind the findobj method in Matplotlib.

Finding object

findobj() 方法可用于查找绘图中的特定类型对象。例如,用户可以搜索 Line2D 实例以识别当前坐标轴中的已绘图线。

The findobj() method can be used to locate specific types of objects within a plot. For example, users can search for Line2D instances to identify plotted lines within the current Axes.

Example

以下示例使用 plot() 方法创建两组线型图,然后你可以使用 findobj() 方法找出与正弦线对应的 Line2D 实例。

The following example creates two sets of line plots using the plot() method then you can use the findobj() method to find out the Line2D instance corresponding to the sinusoidal line.

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import numpy as np

# Generate data
t = np.arange(0, 4, 0.1)
F1 = np.sin(2 * t)
F2 = np.exp(-t*4)

# Plot two lines
fig, ax = plt.subplots(figsize=(7, 4))
line1, = ax.plot(t, F1, 'green', label='Sinusoidal')
line2, = ax.plot(t, F2, 'b--', label='Exponential Decay')

# Find the Line object corresponding to the sinusoidal line
line_handle = plt.gca().findobj(Line2D)[0]

# Display the results
print("Found Line2D instance:", line_handle)

# Display the modified plot
plt.legend()
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

Found Line2D instance: Line2D(Sinusoidal)
findobj demo ex1

Modifying Objects

一旦使用 findobj() 方法定位/识别对象,用户就可以修改其属性以实现所需的视觉效果。这包括更改颜色、线型、文本内容等属性。

Once an object is located/identified using the findobj() method, users can modify its properties to achieve the desired visualization. This includes changing attributes such as color, linestyle, text content, and more.

Example 1

这里有一个示例,它创建一个包含三个文本对象的绘图,其中包含不同的文本内容。 Axes.findobj() 方法用于查找具有特定文本内容('tutorialspoint')的 Text 对象。找到后,文本内容修改为 'Tutorialspoint :)',并且它的颜色被修改为绿色。

Here is an example that creates a plot with three Text objects containing different text content. The Axes.findobj() method is used to locate a Text object with specific text content ('tutorialspoint'). Once found, the text content is modified to 'Tutorialspoint :)' and its color is changed to green.

import matplotlib.pyplot as plt
from matplotlib.text import Text

# Create a plot with a text object
fig, ax = plt.subplots()
ax.text(.4, .5, s='tutorialspoint')
ax.text(.1, .1, s='Python')
ax.text(.8, .8, s='Matplotlib')

# Find the Text object with the text 'tutorialspoint'
text_handle = ax.findobj(
   lambda artist: isinstance(artist, Text) and artist.get_text() == 'tutorialspoint')[0]

# Modify the text
text_handle.set_text('Tutorialspoint :)')
text_handle.set_color('green')
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

findobj demo ex2

用户还可以定义自定义匹配函数,以基于特定标准过滤对象。这样一来,就可以进行更复杂的搜索,并且能高级处理图形对象。

Users can also define custom matching functions to filter objects based on specific criteria. This allows for more complex searches and enables advanced manipulation of graphical objects.

Example 2

这里有另一个示例,演示了如何使用自定义匹配函数通过 Figure.findobj() 方法修改对象。

Here is another example that demonstrates how to use of a custom matching function to modify objects using the Figure.findobj() method.

import matplotlib.pyplot as plt
import matplotlib.text as text
import numpy as np

# Generate data
t = np.arange(0, 4, 0.1)
F1 = np.sin(2 * t)
F2 = np.exp(-t * 4)

# Plot two lines
fig, ax = plt.subplots(figsize=(7, 4))
line1, = ax.plot(t, F1, 'red', label='Sinusoidal')
line2, = ax.plot(t, F2, 'k--', label='Exponential Decay')

plt.grid(False)
plt.xlabel('x label')
plt.ylabel('y label')
plt.title('Modifying the Objects')

# Define a custom function for matching
def myfunc(x):
   return hasattr(x, 'set_color') and not hasattr(x, 'set_facecolor')

# Modify objects based on the custom function
for o in fig.findobj(myfunc):
   o.set_color('green')

# Display the modified plot
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

findobj demo ex3