使用 Matplotlib 库绘图,不能识别鼠标操作,在最前面添加这两行代码
确保 Matplotlib 使用合适的图形后端。在代码中设置后端为 TkAgg 可以帮助解决一些交互问题:
import matplotlib
matplotlib.use(‘TkAgg’)
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import mplcursors
# 创建数据
x = np.linspace(0, 10, 1000)
y = np.sin(x)
# 创建图形和子图
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.3) # 调整底部以放置按钮
line, = ax.plot(x, y, label='sin(x)')
# 添加标题和标签
ax.set_title('Interactive sin(x) plot')
ax.set_xlabel('x')
ax.set_ylabel('sin(x)')
ax.legend()
# 定义按钮的回调函数
class ScaleAxis:
def __init__(self, ax):
self.ax = ax
self.zoom_factor = 1.1 # 缩放因子
def zoom_x_in(self, event):
xlim = self.ax.get_xlim()
x_center = (xlim[0] + xlim[1]) / 2
width = (xlim[1] - xlim[0]) / self.zoom_factor
self.ax.set_xlim([x_center - width / 2, x_center + width / 2])
self.ax.figure.canvas.draw_idle()
def zoom_x_out(self, event):
xlim = self.ax.get_xlim()
x_center = (xlim[0] + xlim[1]) / 2
width = (xlim[1] - xlim[0]) * self.zoom_factor
self.ax.set_xlim([x_center - width / 2, x_center + width / 2])
self.ax.figure.canvas.draw_idle()
def zoom_y_in(self, event):
ylim = self.ax.get_ylim()
y_center = (ylim[0] + ylim[1]) / 2
height = (ylim[1] - ylim[0]) / self.zoom_factor
self.ax.set_ylim([y_center - height / 2, y_center + height / 2])
self.ax.figure.canvas.draw_idle()
def zoom_y_out(self, event):
ylim = self.ax.get_ylim()
y_center = (ylim[0] + ylim[1]) / 2
height = (ylim[1] - ylim[0]) * self.zoom_factor
self.ax.set_ylim([y_center - height / 2, y_center + height / 2])
self.ax.figure.canvas.draw_idle()
def reset(self, event):
self.ax.set_xlim([x[0], x[-1]])
self.ax.set_ylim([y.min(), y.max()])
self.ax.figure.canvas.draw_idle()
# 创建缩放实例
scale = ScaleAxis(ax)
# 创建按钮并绑定事件
ax_zoom_x_in = plt.axes([0.1, 0.05, 0.1, 0.075])
ax_zoom_x_out = plt.axes([0.21, 0.05, 0.1, 0.075])
ax_zoom_y_in = plt.axes([0.32, 0.05, 0.1, 0.075])
ax_zoom_y_out = plt.axes([0.43, 0.05, 0.1, 0.075])
ax_reset = plt.axes([0.54, 0.05, 0.1, 0.075])
btn_zoom_x_in = Button(ax_zoom_x_in, 'Zoom X In')
btn_zoom_x_out = Button(ax_zoom_x_out, 'Zoom X Out')
btn_zoom_y_in = Button(ax_zoom_y_in, 'Zoom Y In')
btn_zoom_y_out = Button(ax_zoom_y_out, 'Zoom Y Out')
btn_reset = Button(ax_reset, 'Reset')
btn_zoom_x_in.on_clicked(scale.zoom_x_in)
btn_zoom_x_out.on_clicked(scale.zoom_x_out)
btn_zoom_y_in.on_clicked(scale.zoom_y_in)
btn_zoom_y_out.on_clicked(scale.zoom_y_out)
btn_reset.on_clicked(scale.reset)
# 使用 mplcursors 显示数据点标签
mplcursors.cursor(line, hover=True)
plt.show()