DEV Community

Cover image for Live figure with jupyter notebook (or pure python file) using matplotlib
bridget462
bridget462

Posted on

1 1

Live figure with jupyter notebook (or pure python file) using matplotlib

Source Codes: https://github.com/bridget462/live-figure

To make a live graph, which update constantly to reflect real-time data, use following method instead of normal plt.show()

The Key methods for live graph are:

  • plt.draw(): to display plot
  • plt.pause(): keep displaying current frame certain duration
  • plt.cla(): to clear previous frame

Use methods above in loop to constantly update figure.


Codes

we only use 2 libraries

import numpy as np # to generate random data
import matplotlib.pyplot as plt # to make figure

# optional (just for figure appearence)
plt.style.use('seaborn-colorblind')
plt.style.use('seaborn-whitegrid')

print('library imported')

if using jupyter, excute command below to create intractive figure instead of displaying in the jupyter cell.

%matplotlib qt

To make live figure, use key methods explained above in loop to update figures. Also replace random number with your actual data.

MEASUREMENT_TIME = 50
INTERVAL_SEC = 0.1

for i in range(MEASUREMENT_TIME):
    # replace with your data
    data = np.random.rand(100)

    plt.plot(data)

    # figure appearence adjustments
    plt.ylim(-0.2, 1.2)
    plt.title(f'FRAME {i+1}')

    # to avoid clearing last plot
    if (i != MEASUREMENT_TIME-1):
        plt.draw()
        plt.pause(INTERVAL_SEC)
        plt.cla()
    else:
        plt.show()

And that's about it. plt.draw(), plt.pause(), plt.cla() can be used to any other figures, such as 3D, polar and etc.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay