问题
I want my figure to have a small entry window, in which the user can type a number, and the data plotted will span that many minutes. If they enter 30, they will look at a 30-minute time window, if they type 5, matplotlib picks this up, data gets trimmed, and only 5 minutes worth of data gets shown.
How can I do this? I noticed that people on SO recommend using TkAgg, is there a way to do this without it? If I do use TkAgg, can you point me to a minimal example that does this in an interactive manner, i.e. picks up new entries that the user makes?
Thank you
EDIT: This is STREAMING data, so I want to condition to be of dynamic form, such as 'give me last 15 minutes' rather than 'give me between 2:10 and 2:25'. Also, I will performing the trimming of the data manually myself, the gui doesn't have to do it. The gui only needs to read a single number and make it available to me.
ONE MORE DETAIL: Don't worry about what happens behind the curtains, I know how to take care of it. All I want to know is simply how to read a number from a text box on a figure in matplotlib.
回答1:
I don't think you can do what you want using a text box without using a 3rd party GUI program. The example below shows how a slider can be used to change the x limits of a plot using just matplotlib itself.
The example used a Slider widget to control the xlimits. You can find another example of using many widgets here.
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()
Below are some plots showing the slider at different positions:
Default (starting) position

Setting the slider to a random value

Setting the slider to the maximum value

来源:https://stackoverflow.com/questions/25449398/matplotlib-user-enters-numeric-input-through-figure