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 numpy 常用函数总结

Numpy是什么 在没给大家介绍numpy之前先给大家说下python的基本概念。 Python 是一种高级的,动态的,多泛型的编程语言。Python代码很多时候看起来就像是伪代码一样...

在linux下实现 python 监控usb设备信号

1. linux下消息记录 关于系统的各种消息一般都会记录在/var/log/messages文件中,有些主机在中默认情况下有可能没有启用,具体配置方法可参考下面这篇博客: 系统日志配置...

Python re模块介绍

Python中转义字符 正则表达式使用反斜杠” \ “来代表特殊形式或用作转义字符,这里跟Python的语法冲突,因此,Python用” \\\\ “表示正则表达式中的” \ “,因为正...

python基于queue和threading实现多线程下载实例

本文实例讲述了python基于queue和threading实现多线程下载的方法,分享给大家供大家参考。具体方法如下: 主代码如下: #download worker qu...

Python实现字符串格式化的方法小结

Python2.6+ 增加了str.format函数,用来代替原有的'%'操作符。它使用比'%'更加直观、灵活。下面详细介绍一下它的使用方法。 下面是使用'%'的例子: "" "P...