Animating a scatter plot with a stationary gap in python

Viewed 136

I'm animating a scatter plot with a code below. It reads data from a .csv file "sample.csv" and animates it by using np.roll in update function.

import numpy as np
import matplotlib.pyplot as plt
from numpy import genfromtxt
from matplotlib.animation import FuncAnimation

my_data = genfromtxt("sample.csv", delimiter=",", skip_header=1)  # reading data

fig, ax = plt.subplots()
xdata, ydata = [], []
line, = ax.plot([], [], ".", markersize=14)
plt.grid()


def init():
    ax.set_xlim(0, 50)
    ax.set_ylim(0, 60)
    return line,


def update(frame):
    my_data[:,0] = np.roll(my_data[:,0],1)  # moving graph
    
    gap_loc = [19,20,21]  # location of a gap
    my_data[gap_loc, 1] = np.nan  # creating a gap in graph
    
    xdata.append(my_data[:,0])
    ydata.append(my_data[:,1])
    
    line.set_data(xdata, ydata)
    return line,

ani = FuncAnimation(fig, update, frames=np.arange(0,50,1), init_func=init, blit=True)
plt.show()

The result looks like that:

enter image description here

As you see there is a gap which moves together with the remaining points. However, what I want to achieve is that the gap was stationary at the locations on the horizontal axis: 19,20,21.

How can I achieve this effect?

Below please find a dataset, I'm using for this animation.

Day,Var 1,Var 2
1,2,12
2,4,19
3,6,20
4,8,25
5,10,25
6,12,33
7,14,40
8,16,47
9,18,49
10,20,50
11,22,52
12,24,55
13,26,65
14,28,82
15,30,100
16,32,100
17,34,110
18,36,117
19,38,140
20,40,145
21,42,164
22,44,170
23,46,198
24,48,200
25,50,210
26,48,210
27,46,211
28,44,216
29,42,267
30,40,317
31,38,325
32,36,335
33,34,337
34,32,347
35,30,356
36,28,402
37,26,410
38,24,448
39,22,449
40,20,457
41,18,463
42,16,494
43,14,500
44,12,501
45,10,502
46,8,514
47,6,551
48,4,551
49,2,558
50,0,628
1 Answers

Define the gap when you load the data, and do so in the x column rather than the y:

# imports

my_data = genfromtxt("sample.csv", delimiter=",", skip_header=1)  # reading data
gap_loc = [19,20,21]  # location of a gap
my_data[gap_loc, 0] = np.nan  # creating a gap in graph

# plotting code

So now when you roll the x column, there will always be np.nan at the x values [19, 20, 21], regardless of what the y coordinate is. You can use print(my_data) within the update function to make clear what was going on each iteration.

Here is the result:

enter image description here

Also, I think you are over-plotting because you continually expand xdata and ydata using append. I ended up just removing the xdata and ydata and doing:

def update(frame):
    my_data[:,0] = np.roll(my_data[:,0],1)  # moving graph
    line.set_data(my_data[:,0], my_data[:,1])
    return line,
Related