import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.text import Text, Annotation
from matplotlib.patches import Polygon, Rectangle, Circle, Arrow, ConnectionPatch,Ellipse,FancyBboxPatch
from matplotlib.widgets import Button, Slider, Widget
def call_move(event, fig): # event mouse press/release
global mPress # whether mouse button press or not
global startx
global starty
# print(mPress)
if event.name=='button_press_event':
axtemp=event.inaxes
# Whether mouse in a coordinate system or not, yes is the figure in the mouse location, no is None
if axtemp and event.button==1:
print(event)
mPress=True
startx=event.xdata
starty=event.ydata
elif event.name=='button_release_event':
axtemp=event.inaxes
if axtemp and event.button==1:
mPress=False
elif event.name=='motion_notify_event':
axtemp=event.inaxes
if axtemp and event.button==1 and mPress: # the mouse continuing press
x_min, x_max = axtemp.get_xlim()
y_min, y_max = axtemp.get_ylim()
w=x_max-x_min
h=y_max-y_min
# mouse movement
mx=event.xdata-startx
my=event.ydata-starty
axtemp.set(xlim=(x_min-mx, x_min-mx+w))
axtemp.set(ylim=(y_min-my, y_min-my+h))
fig.canvas.draw_idle() # Delay drawing
return
def call_scroll(event, fig):
print(event.name)
axtemp=event.inaxes
print('event:',event)
print(event.xdata,event.ydata)
# caculate the xlim and ylim after zooming
if axtemp:
x_min, x_max = axtemp.get_xlim()
y_min, y_max = axtemp.get_ylim()
w = x_max - x_min
h = y_max - y_min
curx=event.xdata
cury=event.ydata
curXposition=(curx - x_min) / w
curYposition=(cury - y_min) / h
# Zoom the figure for 1.1 times
if event.button == 'down':
print('befor:',w,h)
w = w*1.1
h = h*1.1
print('down',w,h)
elif event.button == 'up':
print('befor:',w,h)
w = w/1.1
h = h/1.1
print('up',w,h)
print(curXposition,curYposition)
newx=curx - w*curXposition
newy=cury - h*curYposition
axtemp.set(xlim=(newx, newx+w))
axtemp.set(ylim=(newy, newy+h))
fig.canvas.draw_idle() # drawing
def update_annot(ind, l1, annot, x_str, y_str, fig):
posx = np.array(l1.get_data())[0][ind["ind"][0]] #get the x in the line
posy = np.array(l1.get_data())[1][ind["ind"][0]] #get the y in the line
annot.xy = ([posx, posy])
text = "{}, {}".format(" ".join([x_str[n] for n in ind["ind"]]),
" ".join([y_str[n] for n in ind["ind"]]))
annot.set_text(text)
cmap = plt.cm.RdYlGn
norm = plt.Normalize(1,4)
c = np.random.randint(1,5,size=10) # the upper colour
annot.get_bbox_patch().set_facecolor(cmap(norm(c[ind["ind"][0]])))
annot.get_bbox_patch().set_alpha(0.4)
def hover(event, l1, annot, ax, x_str, y_str, fig):
vis = annot.get_visible()
if event.inaxes == ax:
cont, ind = l1.contains(event)
if cont: # the mouse in the point
update_annot(ind, l1, annot, x_str, y_str, fig)
annot.set_visible(True)
else:
if vis:
annot.set_visible(False)
fig.canvas.draw_idle()
def draw():
fig = plt.figure()
ax = fig.add_subplot(111)
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
x_str = np.array(x).astype(str)
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
y_str = np.array(y).astype(str)
annot = ax.annotate("", xy=(0,0), xytext=(20,20),textcoords="offset points",
bbox=dict(boxstyle="round", fc="w"),
arrowprops=dict(arrowstyle="->"))
plt.ylabel('first')
l1, = plt.plot(x, y)
#l2, = plt.plot(x, y2,color='red',linewidth=1.0,linestyle='--',label='square line')
#plt.legend(handles=[l1, l2], labels=['up', 'down'], loc='upper right')
plt.legend(handles=[l1], labels=['up'], loc='upper right')
annot.set_visible(False) # mouse not display the information when not pointing
plt.grid()
startx=0
starty=0
mPress=False
fig.canvas.mpl_connect('scroll_event', lambda event: call_scroll(event, fig)) # Event mouse wheel
fig.canvas.mpl_connect('button_press_event', lambda event: call_move(event, fig)) # Event mouse button press
fig.canvas.mpl_connect('button_release_event', lambda event: call_move(event, fig)) # Event mouse button release
# fig.canvas.mpl_connect('draw_event', call_move) # Event draw figure
fig.canvas.mpl_connect('motion_notify_event', lambda event: call_move(event, fig)) # Event mouse move
fig.canvas.mpl_connect("motion_notify_event", lambda event: hover(event, l1, annot, ax, x_str, y_str, fig))
x_min = min(x)
x_max = max(x)
y_min = min(y)
y_max = max(y)
ax.set_xlim(x_min, x_max) # xlabel start limition
ax.set_ylim(y_min, y_max) # ylabel start limition
plt.show()
draw()
參考文章:
縮放:python 桌面軟件開(kāi)發(fā)-matplotlib畫圖鼠標(biāo)縮放拖動(dòng)_matplotlib縮放-CSDN博客
獲取點(diǎn)坐標(biāo)參考的文章忘了,侵權(quán)即刪文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-849474.html
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-849474.html
到了這里,關(guān)于Python使用Matplotlib通過(guò)鼠標(biāo)交互實(shí)現(xiàn)縮放、移動(dòng)以及線上點(diǎn)坐標(biāo)顯示功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!