How to use Matplotlib to draw real-time data chart
Editor to share with you how to use Matplotlib to draw real-time data charts, I hope you will learn something after reading this article, let's discuss it together!
Background introduction
You will learn how to chart real-time data using Matplotlib. We will learn how to monitor the constantly updated CSV file and draw the values in the CSV file as the file enters. This is useful for drawing data from API or sensors or any other frequent source. Let's get started.
Dynamically generate data
Next, we simulate the generation of a real-time data and dynamically append it to the data.csv file to see the code implementation:
Import csvimport randomimport time
X_value = 0total_1 = 1000total_2 = 1000fieldnames = ["x_value", "total_1", "total_2"] with open ('data.csv', 'w') as csv_file: csv_writer = csv.DictWriter (csv_file,\ fieldnames=fieldnames) csv_writer.writeheader () while True: with open (' data.csv', 'a') as csv_file: csv_writer = csv.DictWriter (csv_file \ fieldnames=fieldnames) info = {"x_value": x_value, "total_1": total_1, "total_2": total_2} csv_writer.writerow (info) print (x_value, total_1, total_2)
X_value + = 1 total_1 = total_1 + random.randint (- 6,8) total_2 = total_2 + random.randint (- 5,6) time.sleep (1) draw real-time data chart
Let's dynamically read the data.csv file generated above and draw the chart information in real time:
Import pandas as pdimport matplotlib.pyplot as pltfrom matplotlib.animation import FuncAnimation# set style plt.style.use ('fivethirtyeight') x_vals = [] y_vals = [] # define function to read the contents of the csv file def animate (I): data = pd.read_csv (' data.csv') x = data ['xvalued'] y1 = data ['total_1'] y2 = data [' total_2']
Plt.cla () # draw a graph plt.plot (x, y1, label='Channel 1') plt.plot (x, y2, label='Channel 2') plt.legend (loc='upper left') plt.tight_layout () # call the FuncAnimation real-time call function ani = FuncAnimation (plt.gcf (), animate,\ interval=1000) once per second
Plt.tight_layout () plt.show () after reading this article, I believe you have some understanding of "how to use Matplotlib to draw real-time data charts". If you want to know more about it, please follow the industry information channel. Thank you for reading!