Matplotlib 简明教程

hyperlink ,通常称为一个链接,是一个导航元素,在文档或网页中以文本、图像、图标或按钮等多种形式呈现。当单击或激活时,超链接将用户重定向到一个指定的网址或资源,从而创造一个无缝且交互式的体验。

A hyperlink, often referred to as a link, is a navigational element that present in various forms, such as text, images, icons, or buttons, within a document or on a webpage. When clicked or activated, a hyperlink redirects the user to a specified URL or resource, creating a seamless and interactive experience.

Matplotlib 提供了各种工具,用于在绘图中包含超链接。在本教程中,您将探索如何在 Matplotlib 绘图中添加超链接,例如 SVG 图形和 PdfPages。

Matplotlib provides a variety of tools to include hyperlinks in plots. In this tutorial, you will explore how to add hyperlinks in Matplotlib plots, such as SVG figures and PdfPages.

SVG (称为可扩展矢量图形)是一种基于 XML 的图像格式,它支持超链接。但是,必须注意,Matplotlib 中的超链接尤其适用于 SVG 输出。如果绘图保存为静态图像,例如 PNG 或 JPEG,或在窗口中显示为绘图,则超链接功能将不可用。

SVG (known as Scalable Vector Graphics) is an XML-based image format that supports hyperlinks. However, it’s crucial to note that hyperlinks in Matplotlib specifically apply to SVG output. If the plot is saved as a static image, such as PNG or JPEG, or is displayed as plot in a window, the hyperlink functionality will not be operational.

在这种情况下,您可以在具有可单击元素的交互式绘图中使用这一功能。

In such case, you can use this feature in interactive plots with clickable elements.

Example

在这个示例中,创建一个散点图,并使用 set_urls 方法将超链接分配给各个数据点。

In this example, a scatter plot is created, and hyperlinks are assigned to individual data points using the set_urls method.

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
s = plt.scatter([1, 2, 3], [4, 5, 6])
s.set_urls(['https://www.tutorialspoint.com', 'https://www.tutorialspoint.com/matplotlib/index.htm', None])
fig.savefig('scatter.svg')

运行以上代码后,您可以在输出目录中检查.svg图像文件。

After running the above code, you can check the output directory for the .svg image file.

hyperlinks ex1

Matplotlib 中的 PdfPages 模块可以创建多页的 PDF 文档。您可以使用 matplotlib 文本元素为那些 pdf 页面添加超链接。

The PdfPages module in matplotlib enables the creation of multipage PDF documents. You can add hyperlinks to those pdf pages using the matplotlib text elements.

Example

在这个示例中,使用 PdfPage 创建了一个 PDF 文档,并且讲一个带有超链接的文本元素添加到该绘图中。

In this example, a PDF document is created using PdfPages, and a text element with a hyperlink is added to the plot.

import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

msr_line4 = r'$\bf{' + 'Tutorialspoint\ Matplotlib\ Resource : ' + '}$' + "https://www.tutorialspoint.com/matplotlib/index.htm"
with PdfPages('Adding_hyperlink_inside_a_PdfPage.pdf') as pdf:
   plt.figure(figsize=(11, 8.5))

   ax2 = plt.subplot2grid((9, 5), (1, 0), rowspan=1, colspan=2)
   ax2.text(0, 0, msr_line4, fontsize=9)
   plt.axis('off')
   pdf.savefig()
   plt.close

运行以上代码后,您可以在输出目录中检查.pdf文件。

After running the above code, you can check the output directory for the .pdf file.

hyperlinks ex2

对于那些未呈现为 SVG 的绘图(例如显示在 Matplotlib 窗口中的交互式绘图),超链接可以通过事件处理程序实现。通过创建一个函数来处理“pick”事件,您可以定义在单击特定元素时要执行的操作(例如单击数据点)。

For plots that are not rendered as SVG, such as interactive plots displayed in a Matplotlib window, hyperlinks can be implemented using event handlers. By creating a function to handle the "pick" event, you can define actions to be taken when specific elements, like data points, are clicked.

Example

下面的示例演示了如何单击数据点时在浏览器中打开一个指定的超链接。

The following example demonstrates how to open a specified hyperlink in a web browser when clicking on a data point.

import matplotlib.pyplot as plt
import webbrowser

class CustomObject:
   def __init__(self, x, y, name):
      self.x = x
      self.y = y
      self.name = name

def on_pick(event):
   webbrowser.open('https://www.tutorialspoint.com')

# Create custom objects
obj_a = CustomObject(0.1, 0.3, "Object A")
obj_b = CustomObject(0.2, 0.5, "Object B")

# Plotting objects with picker attribute
fig, ax = plt.subplots()
for obj in [obj_a, obj_b]:
   artist = ax.plot(obj.x, obj.y, 'ro', picker=10)[0]
   artist.obj = obj

# Connect pick event to the handler
fig.canvas.callbacks.connect('pick_event', on_pick)

plt.show()

请查看下方的视频,了解输出的外观。

See the below video for how the output looks like.

hyperlinks ex3