Real-time drawing with matplotlib

motivation

There are times when you want to check the values of sensors, or plot the learning status of machine learning on a graph in real time. I want to use python because there is a convenient graph creation library called matplotlib.

Known problems

Normally when making a graph with matplotlib

import matplotlib.pyplot as plt

"""
Processing to calculate the data you want to plot
...
"""
plt.plot(data)
plt.show()

I will do it. However, if you call show (), the program will be blocked there and you will not be able to draw in real time. If you look it up, use articles like draw () instead of show (), or combine it with GUI libraries such as Tkinter (tkinter) and Qt. In the Windows environment, when I touched the graph even once, the GUI got stuck and I couldn't use it though it wasn't very good. (I think it could be used in a Unix environment such as Mac.)

Let's use pause () !!!

As in the example, there was an exchange related to it on stackoverflow. Reference: real-time plotting in while loop with matplotlib

The conclusion is to use plt.pause (interval) instead of plt.show (). Below is an example of plotting a simple sin function forever.

I wrote notes in the comments, so please read them.

matplotlib_realtime_plot_example.py


# -*- coding: utf-8 -*-
"""
Example of real-time plotting with matplotlib

Continue to plot the sin function indefinitely
"""
from __future__ import unicode_literals, print_function

import numpy as np
import matplotlib.pyplot as plt


def pause_plot():
    fig, ax = plt.subplots(1, 1)
    x = np.arange(-np.pi, np.pi, 0.1)
    y = np.sin(x)
    #Must be plot once for initialization
    #At that time, it is necessary to receive the plotted object.
    #Note that list will be returned.
    lines, = ax.plot(x, y)

    #Infinitely plot from here
    while True:
        #Update plot data
        x += 0.1
        y = np.sin(x)

        #If you use the plot function when updating the drawing data
        #Note that the line object will increase each time.
        #
        #The easiest is for the lines received above
        # set_data()How to update drawing data with a method.
        lines.set_data(x, y)

        # set_data()It seems that the axis is not set automatically when using, so
        #In this example, the sin curve disappears from the drawing range in a blink of an eye.
        #Therefore, it is necessary to modify the x-axis range as appropriate.
        ax.set_xlim((x.min(), x.max()))

        #The best point
        # - plt.show()Blocked and cannot be depicted in real time
        # - plt.ion() + plt.draw()Cannot be used because the graph window freezes and the program stops
        # ----> plt.pause(interval)Use this!!!The argument is sleep time
        plt.pause(.01)

if __name__ == "__main__":
    pause_plot()

This will make a lot of progress !!!

bonus

I will introduce the method using the package drawnow in the stackoverflow mentioned above. Since drawnow is entered with pip

$ pip install drawnow

OK.

How to use

matplotlib_drawnow_realtime_plot_example.py


# -*- coding: utf-8 -*-
"""
Example of real-time plotting with matplotlib

Continue to plot the sin function indefinitely
"""
from __future__ import unicode_literals, print_function

import numpy as np
import matplotlib.pyplot as plt
from drawnow import drawnow, figure

def drawnow_plot():
    #Using the figure function included in the drawnow package
    #Create a figure object
    fig = figure()
    x = np.arange(-np.pi, np.pi, .1)
    y = np.sin(x)

    def draw():
        """
Describe the processing required for plot to be passed to the drawnow function
Variables required for plot should be variables in the scope that this function can access
        """
        plt.plot(x, y)

    while True:
        x += .1
        y = np.sin(x)
        drawnow(draw)

... I looked at the source code after writing it, but it seems that drawnow is calling draw () in the end, and it didn't work on Windows (the phenomenon that the GUI freezes). ..

Conclusion

If you want to plot in real time, use plt.pause () !!!

Recommended Posts

Real-time drawing with matplotlib
Graph drawing method with matplotlib
Animation with matplotlib
Japanese with matplotlib
Animation with matplotlib
Histogram with matplotlib
Animate with matplotlib
Try drawing a normal distribution with matplotlib
2-axis plot with Matplotlib
Drawing tips with matplotlib on the server side
Graph drawing using matplotlib
Heatmap with Python + matplotlib
Learn with Cheminformatics Matplotlib
Drawing with Python Tinker
Graph drawing with jupyter (ipython notebook) + matplotlib + vagrant
Various colorbars with Matplotlib
3D plot with matplotlib
Adjust axes with matplotlib
[Python] Customize Colormap when drawing graphs with matplotlib
(For those unfamiliar with Matplotlib) Tips for drawing graphs with Seaborn
Graph Excel data with matplotlib (1)
Try using matplotlib with PyCharm
Graph Excel data with matplotlib (2)
Real-time edge detection with OpenCV
Stackable bar plot with matplotlib
Real-time graph display by matplotlib
Real-time web with Django Channels
Gradient color selection with matplotlib
Animate multiple graphs with matplotlib
Graph drawing with IPython Notebook
Getting Started with Drawing with matplotlib: Creating Diagrams from Data Files
Real-time image processing basics with opencv
Create plot animation with Python + Matplotlib
A python graphing manual with Matplotlib.
Japaneseize Matplotlib with Alpine using Docker
[Python] font family and font with matplotlib
Draw a loose graph with matplotlib
Versatile data plotting with pandas + matplotlib
Heatmap with Dendrogram in Python + matplotlib
3D drawing with SceneKit in Pythonista
Easy Japanese font setting with matplotlib
Easy to draw graphs with matplotlib
Continuously color with matplotlib scatter plot
Draw Lyapunov Fractal with Python, matplotlib
When matplotlib doesn't work with python2.7
Lognormal probability plot with Python, matplotlib
Easy animation with matplotlib (mp4, gif)
Write a stacked histogram with matplotlib
Implement "Data Visualization Design # 2" with matplotlib
How to title multiple figures with matplotlib
Drawing with Bezier curve and Fourier transform
Adjust the spacing between figures with Matplotlib
Align the size of the colorbar with matplotlib
[Python] Drawing a swirl pattern with turtle
Make a partially zoomed figure with matplotlib
Make a drawing quiz with kivy + PyTorch
Write SVG graphs with matplotlib on heroku
Heat Map for Grid Search with Matplotlib
Set the xticklabels color individually with matplotlib
Draw hierarchical axis labels with matplotlib + pandas
[Python] Let's make matplotlib compatible with Japanese