Python matplotlib интерактивный график

matplotlib
Анимация и интерактивный график

С помощью python matplotlib вы можете правильно создавать анимированные графики.

Базовая анимация с FuncAnimation

Пакет matplotlib.animation предлагает несколько классов для создания анимаций. FuncAnimation создает анимации, повторно вызывая функцию. Здесь мы используем функцию animate() которая меняет координаты точки на графике синусоидальной функции.

import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation TWOPI = 2*np.pi fig, ax = plt.subplots() t = np.arange(0.0, TWOPI, 0.001) s = np.sin(t) l = plt.plot(t, s) ax = plt.axis([0,TWOPI,-1,1]) redDot, = plt.plot([0], [np.sin(0)], 'ro') def animate(i): redDot.set_data(i, np.sin(i)) return redDot, # create animation using the animate() function myAnimation = animation.FuncAnimation(fig, animate, frames=np.arange(0.0, TWOPI, 0.1), \ interval=10, blit=True, repeat=True) plt.show() 

Сохранить анимацию в gif

В этом примере мы используем save метод для сохранения Animation объекта с помощью ImageMagick.

import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import rcParams # make sure the full paths for ImageMagick and ffmpeg are configured rcParams['animation.convert_path'] = r'C:\Program Files\ImageMagick\convert' rcParams['animation.ffmpeg_path'] = r'C:\Program Files\ffmpeg\bin\ffmpeg.exe' TWOPI = 2*np.pi fig, ax = plt.subplots() t = np.arange(0.0, TWOPI, 0.001) s = np.sin(t) l = plt.plot(t, s) ax = plt.axis([0,TWOPI,-1,1]) redDot, = plt.plot([0], [np.sin(0)], 'ro') def animate(i): redDot.set_data(i, np.sin(i)) return redDot, # create animation using the animate() function with no repeat myAnimation = animation.FuncAnimation(fig, animate, frames=np.arange(0.0, TWOPI, 0.1), \ interval=10, blit=True, repeat=False) # save animation at 30 frames per second myAnimation.save('myAnimation.gif', writer='imagemagick', fps=30) 

Интерактивные элементы управления с помощью matplotlib.widgets

Для взаимодействия с сюжетами Matplotlib предлагает GUI нейтральных виджеты . Виджеты требуют объекта matplotlib.axes.Axes .

Читайте также:  Create grid in css

Вот демоверсия слайдера, которая ù обновляет амплитуду кривой синуса. Функция обновления активируется событием on_changed() слайдера.

import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib.widgets import Slider TWOPI = 2*np.pi fig, ax = plt.subplots() t = np.arange(0.0, TWOPI, 0.001) initial_amp = .5 s = initial_amp*np.sin(t) l, = plt.plot(t, s, lw=2) ax = plt.axis([0,TWOPI,-1,1]) axamp = plt.axes([0.25, .03, 0.50, 0.02]) # Slider samp = Slider(axamp, 'Amp', 0, 1, valinit=initial_amp) def update(val): # amp is the current value of the slider amp = samp.val # update curve l.set_ydata(amp*np.sin(t)) # redraw canvas while idle fig.canvas.draw_idle() # call update function on slider value change samp.on_changed(update) plt.show() 

Строить живые данные из трубы с помощью matplotlib

Это может быть полезно, когда вы хотите визуализировать входящие данные в режиме реального времени. Эти данные могут, например, поступать от микроконтроллера, который непрерывно сэмплирует аналоговый сигнал.

В этом примере мы получим наши данные из именованного канала (также известного как fifo). В этом примере данные в трубе должны быть числами, разделенными символами новой строки, но вы можете адаптировать их по своему вкусу.

Мы также будем использовать datatype deque из стандартных коллекций библиотек. Объект deque очень похож на список. Но с объектом deque довольно легко добавить что-то к нему, сохраняя при этом объект deque фиксированной длины. Это позволяет нам удерживать ось x на фиксированной длине, а не всегда увеличивать и сжимать график вместе. Дополнительная информация о объектах deque

Выбор правильного бэкэнда имеет жизненно важное значение для производительности. Проверьте, какие серверы работают в вашей операционной системе, и выберите быстрый. Для меня работали только qt4agg и бэкэнд по умолчанию, но по умолчанию он был слишком медленным. Дополнительная информация о бэкэндах в matplotlib

Ни один из символов этого кода не должен удаляться.

import matplotlib import collections #selecting the right backend, change qt4agg to your desired backend matplotlib.use('qt4agg') import matplotlib.pyplot as plt import matplotlib.animation as animation #command to open the pipe datapipe = open('path to your pipe','r') #amount of data to be displayed at once, this is the size of the x axis #increasing this amount also makes plotting slightly slower data_amount = 1000 #set the size of the deque object datalist = collections.deque([0]*data_amount,data_amount) #configure the graph itself fig, ax = plt.subplots() line, = ax.plot([0,]*data_amount) #size of the y axis is set here ax.set_ylim(0,256) def update(data): line.set_ydata(data) return line, def data_gen(): while True: """ We read two data points in at once, to improve speed You can read more at once to increase speed Or you can read just one at a time for improved animation smoothness data from the pipe comes in as a string, and is seperated with a newline character, which is why we use respectively eval and rstrip. """ datalist.append(eval((datapipe.readline()).rstrip('\n'))) datalist.append(eval((datapipe.readline()).rstrip('\n'))) yield datalist ani = animation.FuncAnimation(fig,update,data_gen,interval=0, blit=True) plt.show() 

Если ваш участок начинает задерживаться через некоторое время, попробуйте добавить больше данных datalist.append, чтобы больше строк считывалось каждый кадр. Или выберите более быстрый бэкэнд, если сможете.

Это работало с данными 150 Гц с трубки на моем 1,7 Гц i3 4005u.

Источник

Interactive figures#

When working with data, interactivity can be invaluable. The pan/zoom and mouse-location tools built into the Matplotlib GUI windows are often sufficient, but you can also use the event system to build customized data exploration tools.

Matplotlib ships with backends binding to several GUI toolkits (Qt, Tk, Wx, GTK, macOS, JavaScript) and third party packages provide bindings to kivy and Jupyter Lab. For the figures to be responsive to mouse, keyboard, and paint events, the GUI event loop needs to be integrated with an interactive prompt. We recommend using IPython (see below ).

The pyplot module provides functions for explicitly creating figures that include interactive tools, a toolbar, a tool-tip, and key bindings :

Creates a new empty Figure or selects an existing figure

Creates a new Figure and fills it with a grid of Axes

pyplot has a notion of «The Current Figure» which can be accessed through pyplot.gcf and a notion of «The Current Axes» accessed through pyplot.gca . Almost all of the functions in pyplot pass through the current Figure / Axes (or create one) as appropriate.

Matplotlib keeps a reference to all of the open figures created via pyplot.figure or pyplot.subplots so that the figures will not be garbage collected. Figure s can be closed and deregistered from pyplot individually via pyplot.close ; all open Figure s can be closed via plt.close(‘all’) .

For more discussion of Matplotlib’s event system and integrated event loops:

IPython integration#

We recommend using IPython for an interactive shell. In addition to all of its features (improved tab-completion, magics, multiline editing, etc), it also ensures that the GUI toolkit event loop is properly integrated with the command line (see Command prompt integration ).

In this example, we create and modify a figure via an IPython prompt. The figure displays in a QtAgg GUI window. To configure the integration and enable interactive mode use the %matplotlib magic:

In [1]: %matplotlib Using matplotlib backend: QtAgg In [2]: import matplotlib.pyplot as plt 

Create a new figure window:

Add a line plot of the data to the window:

Change the color of the line from blue to orange:

If you wish to disable automatic redrawing of the plot:

If you wish to re-enable automatic redrawing of the plot:

In recent versions of Matplotlib and IPython , it is sufficient to import matplotlib.pyplot and call pyplot.ion . Using the % magic is guaranteed to work in all versions of Matplotlib and IPython.

Interactive mode#

Return whether plots are updated after every plotting command.

Run the GUI event loop for interval seconds.

Interactive mode controls:

  • whether created figures are automatically shown
  • whether changes to artists automatically trigger re-drawing existing figures
  • when pyplot.show() returns if given no arguments: immediately, or after all of the figures have been closed
  • newly created figures will be displayed immediately
  • figures will automatically redraw when elements are changed
  • pyplot.show() displays the figures and immediately returns

If not in interactive mode:

  • newly created figures and changes to figures are not displayed until
    • pyplot.show() is called
    • pyplot.pause() is called
    • FigureCanvasBase.flush_events() is called

    If you are in non-interactive mode (or created figures while in non-interactive mode) you may need to explicitly call pyplot.show to display the windows on your screen. If you only want to run the GUI event loop for a fixed amount of time, you can use pyplot.pause . This will block the progress of your code as if you had called time.sleep , ensure the current window is shown and re-drawn if needed, and run the GUI event loop for the specified period of time.

    The GUI event loop being integrated with your command prompt and the figures being in interactive mode are independent of each other. If you try to use pyplot.ion without arranging for the event-loop integration, your figures will appear but will not be interactive while the prompt is waiting for input. You will not be able to pan/zoom and the figure may not even render (the window might appear black, transparent, or as a snapshot of the desktop under it). Conversely, if you configure the event loop integration, displayed figures will be responsive while waiting for input at the prompt, regardless of pyplot’s «interactive mode».

    No matter what combination of interactive mode setting and event loop integration, figures will be responsive if you use pyplot.show(block=True) , pyplot.pause , or run the GUI main loop in some other way.

    Using Figure.show it is possible to display a figure on the screen without starting the event loop and without being in interactive mode. This may work (depending on the GUI toolkit) but will likely result in a non-responsive figure.

    Default UI#

    The windows created by pyplot have an interactive toolbar with navigation buttons and a readout of the data values the cursor is pointing at. A number of helpful keybindings are registered by default.

    The following table holds all the default keys, which can be overwritten by use of your matplotlibrc .

    Default key binding and rcParam

    Источник

Оцените статью