0

I'm currently reading data points from a CSV file every 2 seconds and plotting it using matplotlib Funcanimation. However, the date ticks on the x-axis are stacking on top of each other and are therefore unreadable. I'm looking for an efficient way to arrange the x-ticks so they don't stack on top of each other.

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()

Plot

Gracias
  • 45
  • 1
  • 2
  • 6

1 Answers1

1

Assuming that your data is in a date format, e.g. np.datetime64, Have you tried the ConciseDateFormatter from the documentation?

for your example this would be something like

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()
tgpz
  • 161
  • 10