【问题标题】:I am trying to produce a graph that updates in real time and I am getting the output: <Figure size 432x288 with 0 Axes>我正在尝试生成一个实时更新的图表,我得到了输出:<Figure size 432x288 with 0 Axes>
【发布时间】:2020-03-02 04:54:06
【问题描述】:

我正在尝试模仿 matplotlib 教程的结果。我在操作系统环境中工作。据我所知,除了更改 csv 文件的名称以避免覆盖之外,我使用的是教程中代码的精确副本。

用于创建和更新 CSV 的代码是:

import csv
import random
import time

x_value = 0
total_1 = 1000
total_2 = 1000

fieldnames = ["x_value", "total_1", "total_2"]


with open('real_time_data.csv', 'w') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    csv_writer.writeheader()

while True:

    with open('real_time_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)

我用来读取 CSV 并创建和更新图表的代码是:

import random
from itertools import count
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

plt.style.use('fivethirtyeight')

x_vals = []
y_vals = []

index = count()


def animate(i):
    data = pd.read_csv('real_time_data.csv')
    x = data['x_value']
    y1 = data['total_1']
    y2 = data['total_2']

    plt.cla()

    plt.plot(x, y1, label='Channel 1')
    plt.plot(x, y2, label='Channel 2')

    plt.legend(loc='upper left')
    plt.tight_layout()


ani = FuncAnimation(plt.gcf(), animate, interval=1000)

plt.tight_layout()
plt.show()

我得到的不是图表:图形大小为 432x288,轴数为 0。 我将不胜感激任何帮助。谢谢。

【问题讨论】:

    标签: python csv matplotlib


    【解决方案1】:

    您应该在导入 matplotlib 之前添加 %matplotlib inline%matplotlib qt

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-20
      • 2020-01-21
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      相关资源
      最近更新 更多