Matplotlib - 用户通过图形输入数字

1 投票
1 回答
3748 浏览
提问于 2025-04-18 18:11

我想让我的图表有一个小的输入窗口,用户可以在里面输入一个数字,然后图表上显示的数据就会根据这个数字的分钟数来调整。如果他们输入30,就会看到30分钟的时间范围;如果输入5,matplotlib就会自动处理,只显示5分钟的数据。

我该怎么做呢?我注意到很多人在StackOverflow上推荐使用TkAgg,那有没有其他方法可以实现这个功能呢?如果我使用TkAgg,你能给我一个简单的例子吗?这个例子要能实时响应用户的输入,也就是说,能及时获取用户输入的新数字。

谢谢!

补充说明:这是流式数据,所以我希望条件是动态的,比如“给我最近15分钟的数据”,而不是“给我2:10到2:25之间的数据”。另外,我会自己手动处理数据的裁剪,界面不需要做这个。界面只需要读取一个数字,然后把这个数字提供给我。

还有一个细节:不用担心背后的处理过程,我知道怎么处理。我只想知道如何从matplotlib的图表中的文本框读取一个数字。

1 个回答

1

我觉得如果不使用第三方的图形界面程序,你是无法仅通过文本框实现你想要的功能。下面的例子展示了如何仅使用matplotlib这个库,通过滑块来改变图表的x轴范围。

这个例子使用了一个滑块控件来控制x轴的范围。你可以在这里找到另一个使用多个控件的例子。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

# Create some random data
x = np.linspace(0,100,1000)
y = np.sin(x) * np.cos(x)

left, bottom, width, height = 0.15, 0.02, 0.7, 0.10

fig, ax = plt.subplots()

plt.subplots_adjust(left=left, bottom=0.25) # Make space for the slider

ax.plot(x,y)

# Set the starting x limits
xlims = [0, 1]
ax.set_xlim(*xlims)

# Create a plt.axes object to hold the slider
slider_ax = plt.axes([left, bottom, width, height])
# Add a slider to the plt.axes object
slider = Slider(slider_ax, 'x-limits', valmin=0.0, valmax=100.0, valinit=xlims[1])

# Define a function to run whenever the slider changes its value.
def update(val):
    xlims[1] = val
    ax.set_xlim(*xlims)

    fig.canvas.draw_idle()

# Register the function update to run when the slider changes value
slider.on_changed(update)

plt.show()

下面是一些图表,展示了滑块在不同位置的样子:

默认(起始)位置

fig 1

将滑块设置为随机值

fig 2

将滑块设置为最大值

fig 3

撰写回答