【问题标题】:How to extend lines in matplotlib?如何在 matplotlib 中延长线条?
【发布时间】:2022-01-24 01:40:06
【问题描述】:

我编写了一个动画类,它可以接受多行的 y 坐标,我想根据新数据动态扩展它。

问题是,即使我指定了线条标签,它似乎也没有将我的线条视为一个实例。相反,它将它们视为新行。

因此我每次都会得到新的线条颜色和图例:

除了在类中创建一个内部颜色数据库并根据行索引重用它们之外,还有什么方法可以解决此问题?

但我仍然不太喜欢它每次都将我的行视为新实例,我想知道是否有一个简单的解决方法。

import time
from matplotlib import pyplot as plt
import numpy as np

class Animator:
    def __init__(self):
        plt.ion()
        self.fig = plt.figure()
        self.x = 0
        self.Y = np.array([],dtype='object')
        
    def add(self, Y):
        if (self.Y.size == 0 ):
            self.Y = Y
        for i, y in enumerate(Y):
            plt.plot([self.x,self.x+1], [self.Y[i],y], label=f'line{i+1}')
        plt.legend()
        self.x+=1
        self.Y=Y
        self.fig.canvas.flush_events()
        
animator = Animator()   

y_vals = np.random.normal(scale=3,size=(10,3)).cumsum(axis=0)
for i in range(len(y_vals)):
    animator.add(y_vals[i])
    time.sleep(1)

【问题讨论】:

  • 我不确定,但你不应该在冲洗前打电话给self.fig.canvas.draw()吗?
  • 我在init中使用了ion()模式。
  • 好的,更新循环中的值的缩进是否正确?
  • 是的,使用不同类型的循环执行大量计算,然后在每个循环结束时吐出指标。有时可能需要一段时间,所以我需要查看实时数据。
  • 好吧,正如您想象的那样,解决方案是:“在类中创建一个内部颜色数据库并根据行索引重用它们”。为什么你认为这不是一个好主意?

标签: python python-3.x matplotlib


【解决方案1】:

也许它毕竟没有那么糟糕......你觉得呢?

class Animator:
    def __init__(self, style=('b-', 'm--', 'g-.', 'r:')):
        plt.ion()
        self.fig = plt.figure()
        self.x = 0
        self.Y = np.array([],dtype='object')
        self.fmts=lambda a: style[a%len(style)]
        
    def add(self, Y):
        if (self.Y.size == 0 ):
            self.Y = Y
        for i, y in enumerate(Y):
            plt.plot([self.x,self.x+1], [self.Y[i],y], self.fmts(i), label=f'line{i+1}')
        if (self.x==0):
            plt.legend(loc='upper left')
        self.x+=1
        self.Y=Y
        self.fig.canvas.flush_events()

【讨论】:

    猜你喜欢
    • 2016-03-05
    • 1970-01-01
    • 2019-02-28
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 2016-07-27
    相关资源
    最近更新 更多