【问题标题】:Variable date ticks matplotlib animation可变日期刻度 matplotlib 动画
【发布时间】:2021-07-09 20:41:37
【问题描述】:

我目前每 2 秒从 CSV 文件中读取数据点,并使用 matplotlib Funcanimation 绘制它。但是,x 轴上的日期刻度相互堆叠,因此不可读。我正在寻找一种有效的方法来排列 x-ticks,这样它们就不会堆叠在一起。

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

def animate(i):
    data = pd.read_csv('data.csv')
    x = data.iloc[:,0]
    y4 = data.iloc[:,4]
    plt.cla()
    plt.plot(x, y4, label = "value")
    
    plt.legend(loc= 'upper left')
    plt.tight_layout()

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

plt.show()

【问题讨论】:

    标签: python matplotlib matplotlib-animation


    【解决方案1】:

    假设您的数据采用日期格式,例如np.datetime64,您是否尝试过 the documentation 的 ConciseDateFormatter?

    对于您的示例,这将类似于

    import matplotlib.dates as mdates
    def animate(i):
        data = pd.read_csv('data.csv')
        x = data.iloc[:,0]
        y4 = data.iloc[:,4]
        plt.cla()
    
        ax = plt.gca()
        locator = mdates.AutoDateLocator(minticks=3, maxticks=7)
        formatter = mdates.ConciseDateFormatter(locator)
        ax.xaxis.set_major_locator(locator)
        ax.xaxis.set_major_formatter(formatter)
    
        plt.plot(x, y4, label = "value")
        
        plt.legend(loc= 'upper left')
        plt.tight_layout()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 2015-06-28
      • 2012-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多