当前位置:   article > 正文

Python使用Matplotlib通过鼠标交互实现缩放、移动以及线上点坐标显示功能_matplotlib缩放交互

matplotlib缩放交互
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib as mpl
  4. from matplotlib.text import Text, Annotation
  5. from matplotlib.patches import Polygon, Rectangle, Circle, Arrow, ConnectionPatch,Ellipse,FancyBboxPatch
  6. from matplotlib.widgets import Button, Slider, Widget
  7. def call_move(event, fig): # event mouse press/release
  8. global mPress # whether mouse button press or not
  9. global startx
  10. global starty
  11. # print(mPress)
  12. if event.name=='button_press_event':
  13. axtemp=event.inaxes
  14. # Whether mouse in a coordinate system or not, yes is the figure in the mouse location, no is None
  15. if axtemp and event.button==1:
  16. print(event)
  17. mPress=True
  18. startx=event.xdata
  19. starty=event.ydata
  20. elif event.name=='button_release_event':
  21. axtemp=event.inaxes
  22. if axtemp and event.button==1:
  23. mPress=False
  24. elif event.name=='motion_notify_event':
  25. axtemp=event.inaxes
  26. if axtemp and event.button==1 and mPress: # the mouse continuing press
  27. x_min, x_max = axtemp.get_xlim()
  28. y_min, y_max = axtemp.get_ylim()
  29. w=x_max-x_min
  30. h=y_max-y_min
  31. # mouse movement
  32. mx=event.xdata-startx
  33. my=event.ydata-starty
  34. axtemp.set(xlim=(x_min-mx, x_min-mx+w))
  35. axtemp.set(ylim=(y_min-my, y_min-my+h))
  36. fig.canvas.draw_idle() # Delay drawing
  37. return
  38. def call_scroll(event, fig):
  39. print(event.name)
  40. axtemp=event.inaxes
  41. print('event:',event)
  42. print(event.xdata,event.ydata)
  43. # caculate the xlim and ylim after zooming
  44. if axtemp:
  45. x_min, x_max = axtemp.get_xlim()
  46. y_min, y_max = axtemp.get_ylim()
  47. w = x_max - x_min
  48. h = y_max - y_min
  49. curx=event.xdata
  50. cury=event.ydata
  51. curXposition=(curx - x_min) / w
  52. curYposition=(cury - y_min) / h
  53. # Zoom the figure for 1.1 times
  54. if event.button == 'down':
  55. print('befor:',w,h)
  56. w = w*1.1
  57. h = h*1.1
  58. print('down',w,h)
  59. elif event.button == 'up':
  60. print('befor:',w,h)
  61. w = w/1.1
  62. h = h/1.1
  63. print('up',w,h)
  64. print(curXposition,curYposition)
  65. newx=curx - w*curXposition
  66. newy=cury - h*curYposition
  67. axtemp.set(xlim=(newx, newx+w))
  68. axtemp.set(ylim=(newy, newy+h))
  69. fig.canvas.draw_idle() # drawing
  70. def update_annot(ind, l1, annot, x_str, y_str, fig):
  71. posx = np.array(l1.get_data())[0][ind["ind"][0]] #get the x in the line
  72. posy = np.array(l1.get_data())[1][ind["ind"][0]] #get the y in the line
  73. annot.xy = ([posx, posy])
  74. text = "{}, {}".format(" ".join([x_str[n] for n in ind["ind"]]),
  75. " ".join([y_str[n] for n in ind["ind"]]))
  76. annot.set_text(text)
  77. cmap = plt.cm.RdYlGn
  78. norm = plt.Normalize(1,4)
  79. c = np.random.randint(1,5,size=10) # the upper colour
  80. annot.get_bbox_patch().set_facecolor(cmap(norm(c[ind["ind"][0]])))
  81. annot.get_bbox_patch().set_alpha(0.4)
  82. def hover(event, l1, annot, ax, x_str, y_str, fig):
  83. vis = annot.get_visible()
  84. if event.inaxes == ax:
  85. cont, ind = l1.contains(event)
  86. if cont: # the mouse in the point
  87. update_annot(ind, l1, annot, x_str, y_str, fig)
  88. annot.set_visible(True)
  89. else:
  90. if vis:
  91. annot.set_visible(False)
  92. fig.canvas.draw_idle()
  93. def draw():
  94. fig = plt.figure()
  95. ax = fig.add_subplot(111)
  96. x = np.array([2597.0, 2232.0, 2022.0, 1781.0, 1569.0, 1319.0, 1132.0, 946.0, 743.0, 532.0]) #get x
  97. x_str = np.array(x).astype(str)
  98. y = np.array([696.9, 623.8, 550.8, 477.7, 404.6, 328.8, 255.7, 182.7, 109.6, 36.5])# get y
  99. y_str = np.array(y).astype(str)
  100. annot = ax.annotate("", xy=(0,0), xytext=(20,20),textcoords="offset points",
  101. bbox=dict(boxstyle="round", fc="w"),
  102. arrowprops=dict(arrowstyle="->"))
  103. plt.ylabel('first')
  104. l1, = plt.plot(x, y)
  105. #l2, = plt.plot(x, y2,color='red',linewidth=1.0,linestyle='--',label='square line')
  106. #plt.legend(handles=[l1, l2], labels=['up', 'down'], loc='upper right')
  107. plt.legend(handles=[l1], labels=['up'], loc='upper right')
  108. annot.set_visible(False) # mouse not display the information when not pointing
  109. plt.grid()
  110. startx=0
  111. starty=0
  112. mPress=False
  113. fig.canvas.mpl_connect('scroll_event', lambda event: call_scroll(event, fig)) # Event mouse wheel
  114. fig.canvas.mpl_connect('button_press_event', lambda event: call_move(event, fig)) # Event mouse button press
  115. fig.canvas.mpl_connect('button_release_event', lambda event: call_move(event, fig)) # Event mouse button release
  116. # fig.canvas.mpl_connect('draw_event', call_move) # Event draw figure
  117. fig.canvas.mpl_connect('motion_notify_event', lambda event: call_move(event, fig)) # Event mouse move
  118. fig.canvas.mpl_connect("motion_notify_event", lambda event: hover(event, l1, annot, ax, x_str, y_str, fig))
  119. x_min = min(x)
  120. x_max = max(x)
  121. y_min = min(y)
  122. y_max = max(y)
  123. ax.set_xlim(x_min, x_max) # xlabel start limition
  124. ax.set_ylim(y_min, y_max) # ylabel start limition
  125. plt.show()
  126. draw()

参考文章:

缩放:python 桌面软件开发-matplotlib画图鼠标缩放拖动_matplotlib缩放-CSDN博客

获取点坐标参考的文章忘了,侵权即删

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/371284?site
推荐阅读
相关标签
  

闽ICP备14008679号