【问题标题】:Python Realtime Plotting from csv file来自csv文件的Python实时绘图
【发布时间】:2021-08-20 04:07:13
【问题描述】:

我从 GitHub Link here 获得此代码。

我使用 data_gen 代码生成随机数并不断将这些数字写入 CSV 文件。 然后,我使用 sn-ps.txt 中的代码进行实时绘图。

我正在使用 Colab 环境来运行这两个代码,并且都在同一个目录中。 我面临的问题是代码没有实时显示绘图,而是在我中断 data_gen 代码后绘制保存在 CSV 文件中的数据。

这是两个代码:

第一个代码:

# data_gen code
    import csv
    import random
    import time
    import matplotlib.pyplot as plt
    
    x_value = 0
    total_1 = 1000
    total_2 = 1000
    
    fieldnames = ["x_value", "total_1", "total_2"]
    
    with open('/content/gdrive/MyDrive/data_ranadom.csv', 'w') as csv_file:
        csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        csv_writer.writeheader()
    
    while True:
        with open('/content/gdrive/MyDrive/data_ranadom.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)

第二个代码:

# Data_plot code
import os
import random
from itertools import count
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

plt.ion()
plt.style.use('fivethirtyeight')

x_vals = []
y_vals = []

plt.plot([], [], label='Channel 1')
plt.plot([], [], label='Channel 2')

def animate(i):
    data = pd.read_csv('/content/gdrive/MyDrive/data_ranadom.csv')
    x = data['x_value']
    y1 = data['total_1']
    y2 = data['total_2']

    ax = plt.gca()
    line1, line2 = ax.lines

    line1.set_data(x, y1)
    line2.set_data(x, y2)

    xlim_low, xlim_high = ax.get_xlim()
    ylim_low, ylim_high = ax.get_ylim()

    ax.set_xlim(xlim_low, (x.max() + 5))

    y1max = y1.max()
    y2max = y2.max()
    current_ymax = y1max if (y1max > y2max) else y2max

    y1min = y1.min()
    y2min = y2.min()
    current_ymin = y1min if (y1min < y2min) else y2min

    ax.set_ylim((current_ymin - 5), (current_ymax + 5))


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

plt.legend()
plt.tight_layout()
plt.show()

data_gen 代码似乎按预期工作,即生成随机数并将它们存储在 CVS 文件中。

我猜问题出在 data_plot 代码中,因为它似乎没有实时监控 CSV 文件。相反,它将保存的数据绘制在 CSV 文件中。虽然,代码在 coder youtube 频道 (Tutorial Link here) 中运行良好。

有人能帮我找到修改代码以使其正常工作的方法吗?

我尝试将%%writefile test2.py 用于data_plot 代码,然后使用!python '/content/gdrive/MyDrive/test2.py' 在data_gen 代码中调用此python 脚本,但它没有显示任何绘图。

【问题讨论】:

  • 您是否尝试在本地运行这两个脚本?

标签: python csv matplotlib real-time matplotlib-animation


【解决方案1】:

对于第二个脚本,你必须创建一个循环来每两三秒绘制一次,你还必须使用plt.pause() 给 Matplotlib 绘制时间。

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

plt.ion()
plt.style.use('fivethirtyeight')

x_vals = []
y_vals = []

plt.plot([], [], label='Channel 1')
plt.plot([], [], label='Channel 2')

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

    ax = plt.gca()
    line1, line2 = ax.lines

    line1.set_data(x, y1)
    line2.set_data(x, y2)

    xlim_low, xlim_high = ax.get_xlim()
    ylim_low, ylim_high = ax.get_ylim()

    ax.set_xlim(xlim_low, (x.max() + 5))

    y1max = y1.max()
    y2max = y2.max()
    current_ymax = y1max if (y1max > y2max) else y2max

    y1min = y1.min()
    y2min = y2.min()
    current_ymin = y1min if (y1min < y2min) else y2min

    ax.set_ylim((current_ymin - 5), (current_ymax + 5))


while True:
    
    ani = FuncAnimation(plt.gcf(), animate, interval=1000)
    
    plt.legend()
    plt.tight_layout()
    plt.pause(3) # Number of seconds you wait to update the plot

顺便说一句,当我关闭窗口时,它无法再次显示情节,这很奇怪。也许你可以解决这个问题。

【讨论】:

  • 感谢您的回答。它不适用于colab环境。我猜最简单的方法是在本地运行这两个脚本,它应该可以工作。
猜你喜欢
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 1970-01-01
  • 2015-04-29
  • 2018-09-02
  • 2018-05-22
  • 2020-05-21
  • 2018-07-27
相关资源
最近更新 更多