python+matplotlib实现鼠标移动三角形高亮及索引显示

yipeiwu_com6年前Python基础

Trifinder事件实例

实例展示Trifinder对象对的使用。当鼠标移动到一个被分割的三角形上,这个三角形高亮显示,并且它的标签在图标题显示。

展示下演示结果:

完整代码:

import matplotlib.pyplot as plt
from matplotlib.tri import Triangulation
from matplotlib.patches import Polygon
import numpy as np


def update_polygon(tri):
  if tri == -1:
    points = [0, 0, 0]
  else:
    points = triang.triangles[tri]
  xs = triang.x[points]
  ys = triang.y[points]
  polygon.set_xy(list(zip(xs, ys)))


def motion_notify(event):
  if event.inaxes is None:
    tri = -1
  else:
    tri = trifinder(event.xdata, event.ydata)
  update_polygon(tri)
  plt.title('In triangle %i' % tri)
  event.canvas.draw()


# Create a Triangulation.
n_angles = 16
n_radii = 5
min_radius = 0.25
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi / n_angles
x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()
triang = Triangulation(x, y)
triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
             y[triang.triangles].mean(axis=1))
        < min_radius)

# Use the triangulation's default TriFinder object.
trifinder = triang.get_trifinder()

# Setup plot and callbacks.
plt.subplot(111, aspect='equal')
plt.triplot(triang, 'bo-')
polygon = Polygon([[0, 0], [0, 0]], facecolor='y') # dummy data for xs,ys
update_polygon(-1)
plt.gca().add_patch(polygon)
plt.gcf().canvas.mpl_connect('motion_notify_event', motion_notify)
plt.show()

总结

本文所示是一个Python+matplotlib实现的简单实例,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

Python 虚拟空间的使用代码详解

Python 虚拟空间的使用代码详解

具体代码如下所示: # 在项目根目录创建 python3 -m venv 虚拟空间名称 ## 如 python3 -m venv myvenv # 对于 macOS ## 在项目根...

Python 3 使用Pillow生成漂亮的分形树图片

Python 3 使用Pillow生成漂亮的分形树图片

该程序通过绘制树干(最初是树;后来是树枝)并递归地添加树来绘制“树”。 使用Pillow。 利用递归函数绘制分形树(fractal tree),分形几何学的基本思想:客观事物具有自相似的...

python实现邮件发送功能

什么是POP3、SMTP和MAP? POP3是Post Office Protocol 3的简称,即邮局协议的第三个版本,他是规定怎样将个人计算机连接到Internet的邮件服务器和下载...

TensorFlow深度学习之卷积神经网络CNN

TensorFlow深度学习之卷积神经网络CNN

一、卷积神经网络的概述 卷积神经网络(ConvolutionalNeural Network,CNN)最初是为解决图像识别等问题设计的,CNN现在的应用已经不限于图像和视频,也可用于时间...

python下实现二叉堆以及堆排序的示例

堆是一种特殊的树形结构, 堆中的数据存储满足一定的堆序。堆排序是一种选择排序, 其算法复杂度, 时间复杂度相对于其他的排序算法都有很大的优势。 堆分为大头堆和小头堆, 正如其名, 大头堆...