Skip to main content
 首页 » 编程设计

python之MatPlotLib 动态时间轴

2024年10月25日12lyj

我已经研究了一段时间,但没有找到我正在寻找的解决方案。

有没有一种方法可以使用 matplotlib 创建动态 x 轴?我有一个正在绘制数据流的图表,我想让 x 轴显示耗时(当前是静态的 0-100,而图表的其余部分更新为我的数据流)。

理想情况下,每个刻度间隔 0.5 秒,显示最新的 10 秒。该程序将全天候运行 24/7,因此我可以将其设置为实际时间而不是秒表时间。我在研究中只发现了静态日期时间轴。

如有必要,我可以提供代码,但对于这个问题似乎没有必要。

请您参考如下方法:

因为我不知道你在流什么,我写了一个通用的例子,它可能会帮助你解决你的问题。

from pylab import * 
import matplotlib.animation as animation 
 
class Monitor(object): 
    """  This is supposed to be the class that will capture the data from 
        whatever you are doing. 
    """     
    def __init__(self,N): 
        self._t    = linspace(0,100,N) 
        self._data = self._t*0 
 
    def captureNewDataPoint(self): 
        """  The function that should be modified to capture the data 
            according to your needs 
        """  
        return 2.0*rand()-1.0 
 
 
    def updataData(self): 
        while True: 
            self._data[:]  = roll(self._data,-1) 
            self._data[-1] = self.captureNewDataPoint() 
            yield self._data 
 
class StreamingDisplay(object): 
 
    def __init__(self): 
        self._fig = figure() 
        self._ax  = self._fig.add_subplot(111) 
 
    def set_labels(self,xlabel,ylabel): 
        self._ax.set_xlabel(xlabel) 
        self._ax.set_ylabel(ylabel) 
 
    def set_lims(self,xlim,ylim): 
        self._ax.set_xlim(xlim) 
        self._ax.set_ylim(ylim) 
 
    def plot(self,monitor): 
        self._line, = (self._ax.plot(monitor._t,monitor._data)) 
 
    def update(self,data): 
        self._line.set_ydata(data) 
        return self._line 
 
# Main 
if __name__ == '__main__': 
    m = Monitor(100) 
    sd = StreamingDisplay() 
    sd.plot(m) 
    sd.set_lims((0,100),(-1,1)) 
 
    ani = animation.FuncAnimation(sd._fig, sd.update, m.updataData, interval=500) # interval is in ms 
    plt.show() 

希望对你有帮助