How to show only 'x' amount of values on a graph in python

拟墨画扇 提交于 2021-01-29 10:57:24

问题


I am new to python and am carrying out some little projects along side watching tutorials to enable me to learn.

I have recently been working with some APIs to collect data - I save this data in a CSV file and then open the CSV file to show the data as a graph.

I want the graph to show the data LIVE, but in doing so I only want 10 values on the screen at once, so when the 11th value is plotted, the 1st is no longer visible unless the scrolling function is used to look back at it..

I have managed to pull together the code that plots the live data from the CSV file, as well as some code that creates the graph in the desired format - but as I am quite new to python I am unsure of how I'd make them work together.. Any advice would be greatly appreciated.

Below is the code that I have created to read and plot from a CSV file:

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

index = count()

def animate(i):
    data = pd.read_csv('x.csv')
    x = data['Time']
    y = data['R1Temp']
    y1 = data['R2Temp']
    y2 = data['R3Temp']

    plt.cla()

    plt.plot(x, y, marker = 'o', label='Room 1 Temp')
    plt.plot(x, y1, marker = 'o', label='Room 2 Temp')
    plt.plot(x, y2, marker = 'o', label='Room 3 Temp')   

    plt.xlabel("Time")
    
    plt.ylabel("Temperature °C")
    plt.title("Live temperature of Rooms")
    
    plt.legend(loc='upper left')
    plt.tight_layout()


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

plt.tight_layout()
plt.show()

Below is the code that shows the way in which I'd like the graph to format the data plots:

import numpy as np
import matplotlib.pyplot as plt

import matplotlib.animation as animation


def update(frame):
    global x, y

    start = x[max(frame-PAN//2, 0)] 
    start = x[max(frame-PAN+1, 0)] 
    end = start + PAN

    ax.set_xlim(start, end)

    start, end = ax.get_xlim()
    ax.xaxis.set_ticks(np.arange(start, end, TICK))

    ax.figure.canvas.draw()

    line1.set_data(x[0:frame+1], y[0:frame+1])

    return (line1,)

# main
NUM = 100
TICK = 1
PAN = 10

x = np.arange(start=1, stop=NUM + 1, step=1)

for i in range(NUM):
    y = np.random.rand(NUM) * 100

fig, ax = plt.subplots()

ax.set_xlim(0, PAN)
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, TICK))

ax.set_ylim(0, 100)

line1, = ax.plot([], [], color="r")

ani = animation.FuncAnimation(fig, update, frames=len(x), interval=1000, repeat=False)

plt.show()

I have tried many ways to merge them together, but I just cant seem to find the correct way to go about it.

Thanks in advance!!


回答1:


Showing the last N time points is quite easy. Just use DataFrame.tail() to get the last N rows of your dataframe.

Note that when doing an animation, the recommended way is to create your axes and artists outside the animation code, and only update your artists' data inside the animate code.

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation


fig, ax = plt.subplots()

l1, = ax.plot([], [], marker='o', label='Room 1 Temp')
l2, = ax.plot([], [], marker='o', label='Room 2 Temp')
l3, = ax.plot([], [], marker='o', label='Room 3 Temp')

plt.xlabel("Time")
plt.ylabel("Temperature °C")
plt.title("Live temperature of Rooms")
plt.legend(loc='upper left')
plt.tight_layout()


def animate(i, N):
    data = pd.read_csv('x.csv').tail(N)

    l1.set_data(data['Time'], data['R1Temp'])
    l2.set_data(data['Time'], data['R2Temp'])
    l3.set_data(data['Time'], data['R3Temp'])

    ax.relim()
    ax.autoscale_view()

    return l1, l2, l3


ani = FuncAnimation(fig, animate, interval=1000, frames=None, fargs=(10,))

plt.show()


来源:https://stackoverflow.com/questions/65506641/how-to-show-only-x-amount-of-values-on-a-graph-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!