usag1r
usag1r

Reputation: 124

Matplotlib x-axis dynamic range update

I've been trying to create a matplotlib animation with FuncAnimation.

The code below creates a simple animated line chart.

If this code runs all day (let's suppose it's tracking a stock price), chart will become too loaded with data and it won't be readable at all. (see attached image) To overcome this problem I was trying to update the x-axis dynamically as below so that the start of the x axis is increased by a value in every iteration but I can't get it to work.

Here is the line that causes the error:

plt.axes().set_xlim([index,100])

And the full code:

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

random.seed(234324234234)

x = []
y = []

plt.style.use("fivethirtyeight")

index = count()

def animate(i):
    x.append(next(index))
    y.append(random.randint(0,3))

    plt.cla()
    plt.plot(x,y)
    #plt.axes().set_xlim([index,100])

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

plt.tight_layout()
plt.show()

Image: image

Upvotes: 1

Views: 2786

Answers (1)

Zachwhitman
Zachwhitman

Reputation: 48

You can easily achieve this by adding pyplot.xlim method to your function (pyplot.ylim as well if needed). Xlim and ylim methods are used to define lower and upper limits of axes for matplotlib pyplot charts.

Dynamically updating axes:

If you define arguments of xlim with a constant your axes will be fixed but your Python code is specifically suitable to use the iterator i as the upper and/or lower limit value of xlim. For example:

def animate(i):
    x.append(next(index))
    y.append(random.randint(0,3))

    plt.cla()
    plt.plot(x,y)
    plt.xlim(i-20, i+10)

Just adjust the values to subtract and add as these values will define the margin before and after your most recent data point on the chart regarding x-axis.

Using the same technique you can also create a dynamically moving y-axis with including ylim in your function.

You can use both the example above and directly apply xlim to the plot figure as:

plt.xlim(i-20, i+10)

You can also use the axes method such as:

axes.set_xlim(i-20, i+10)

Source: Matplotlib Example with Dynamic Axis

Official Matplotlib API Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.xlim.html

Upvotes: 1

Related Questions