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

yipeiwu_com5年前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 OpenCV获取视频的方法

之前有文章,使用Android平台的OpenCV接入了视频,控制的目标是手机的摄像头,这是OpenCV的好处,使用OpenCV可以使用跨平台的接口实现相同的功能,减少了平台间移植的困难。...

python正则实现提取电话功能

本文实例为大家分享了python正则提取电话的具体代码,供大家参考,具体内容如下 主要用到正则 import re import xlrd def is_number(s):#是...

Django框架中序列化和反序列化的例子

1.序列化 DRF的核心 就是 前后端分离的核心 前后端分离开发的核心: 将模型转换为json 称之为 序列化 将json转换为模型 称之为 反序列化 1.序列化器的字段 Seriali...

python字典DICT类型合并详解

python字典DICT类型合并详解

本文为大家分享了python字典DICT类型合并的方法,供大家参考,具体内容如下 我要的字典的键值有些是数据库中表的字段名, 但是有些却不是, 我需要把它们整合到一起, 因此有些这篇文章...

Python+OpenCV 实现图片无损旋转90°且无黑边

Python+OpenCV 实现图片无损旋转90°且无黑边

0. 引言 有如上一张图片,在以往的图像旋转处理中,往往得到如图所示的图片。 然而,在进行一些其他图像处理或者图像展示时,黑边带来了一些不便。本文解决图片旋转后出现黑边的问题,实现了...