Python Matplotlib Update ScatterMake a point move on the plot without clearing earlier plots in matplotlibDraw a circle on the plot that follows the mouseScatter animation in PythonCalling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?How do you change the size of figures drawn with matplotlib?Does Python have a ternary conditional operator?How to get the current time in PythonHow can I make a time delay in Python?Does Python have a string 'contains' substring method?
How do I type a hyphen in iOS 12?
Does it make sense to use a wavelet that is equal to a sine of one period?
How do I make a Magical Dart Thrower more economical in Adventurers League?
Why did the World Bank set the global poverty line at $1.90?
Forgot passport for Alaska cruise (Anchorage to Vancouver)
How to avoid typing 'git' at the begining of every Git command
How to make a composition of functions prettier?
Do SFDX commands count toward limits?
5 band resistor. Red, orange, black, gold and black. It doesn't fit in to normal rules
That's not my X, its Y is too Z
Why is the distribution of dark matter in a Galaxy different from the distribution of normal matter?
How to generate list of *all* available commands and functions?
What's the difference between DHCP and NAT? Are they mutually exclusive?
Is it true that "only photographers care about noise"?
What is Gilligan's full Name?
Why do (or did, until very recently) aircraft transponders wait to be interrogated before broadcasting beacon signals?
Print "N NE E SE S SW W NW"
What is the STRONGEST end-of-line knot to use if you want to use a steel-thimble at the end, so that you've got a steel-eyelet at the end of the line?
Realistic, logical way for men with medieval-era weaponry to compete with much larger and physically stronger foes
Who is "He that flies" in Lord of the Rings?
Open Drain pin not going to GND
In Pandemic, why take the extra step of eradicating a disease after you've cured it?
Professor Roman loves to teach unorthodox Chemistry
What do you call the action of "describing events as they happen" like sports anchors do?
Python Matplotlib Update Scatter
Make a point move on the plot without clearing earlier plots in matplotlibDraw a circle on the plot that follows the mouseScatter animation in PythonCalling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?How do you change the size of figures drawn with matplotlib?Does Python have a ternary conditional operator?How to get the current time in PythonHow can I make a time delay in Python?Does Python have a string 'contains' substring method?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I tried to write a simple script which updates a scatter plot for every timestep t. I wanted to do it as simple as possible. But all it does is to open a window where I can see nothing. The window just freezes. It is maybe just an small error, but I can not find it.
The the data.dat has the format
x y
Timestep 1 1 2
3 1
Timestep 2 6 3
2 1
(the file contains just the numbers)
import numpy as np
import matplotlib.pyplot as plt
import time
# Load particle positioins
with open('//home//user//data.dat', 'r') as fp:
particles = []
for line in fp:
line = line.split()
if line:
line = [float(i) for i in line]
particles.append(line)
T = 100
numbParticles = 2
x, y = np.array([]), np.array([])
plt.ion()
plt.figure()
plt.scatter(x,y)
for t in range(T):
plt.clf()
for k in range(numbP):
x = np.append(x, particles[numbParticles*t+k][0])
y = np.append(y, particles[numbParticles*t+k][1])
plt.scatter(x,y)
plt.draw()
time.sleep(1)
x, y = np.array([]), np.array([])
python matplotlib
add a comment |
I tried to write a simple script which updates a scatter plot for every timestep t. I wanted to do it as simple as possible. But all it does is to open a window where I can see nothing. The window just freezes. It is maybe just an small error, but I can not find it.
The the data.dat has the format
x y
Timestep 1 1 2
3 1
Timestep 2 6 3
2 1
(the file contains just the numbers)
import numpy as np
import matplotlib.pyplot as plt
import time
# Load particle positioins
with open('//home//user//data.dat', 'r') as fp:
particles = []
for line in fp:
line = line.split()
if line:
line = [float(i) for i in line]
particles.append(line)
T = 100
numbParticles = 2
x, y = np.array([]), np.array([])
plt.ion()
plt.figure()
plt.scatter(x,y)
for t in range(T):
plt.clf()
for k in range(numbP):
x = np.append(x, particles[numbParticles*t+k][0])
y = np.append(y, particles[numbParticles*t+k][1])
plt.scatter(x,y)
plt.draw()
time.sleep(1)
x, y = np.array([]), np.array([])
python matplotlib
add a comment |
I tried to write a simple script which updates a scatter plot for every timestep t. I wanted to do it as simple as possible. But all it does is to open a window where I can see nothing. The window just freezes. It is maybe just an small error, but I can not find it.
The the data.dat has the format
x y
Timestep 1 1 2
3 1
Timestep 2 6 3
2 1
(the file contains just the numbers)
import numpy as np
import matplotlib.pyplot as plt
import time
# Load particle positioins
with open('//home//user//data.dat', 'r') as fp:
particles = []
for line in fp:
line = line.split()
if line:
line = [float(i) for i in line]
particles.append(line)
T = 100
numbParticles = 2
x, y = np.array([]), np.array([])
plt.ion()
plt.figure()
plt.scatter(x,y)
for t in range(T):
plt.clf()
for k in range(numbP):
x = np.append(x, particles[numbParticles*t+k][0])
y = np.append(y, particles[numbParticles*t+k][1])
plt.scatter(x,y)
plt.draw()
time.sleep(1)
x, y = np.array([]), np.array([])
python matplotlib
I tried to write a simple script which updates a scatter plot for every timestep t. I wanted to do it as simple as possible. But all it does is to open a window where I can see nothing. The window just freezes. It is maybe just an small error, but I can not find it.
The the data.dat has the format
x y
Timestep 1 1 2
3 1
Timestep 2 6 3
2 1
(the file contains just the numbers)
import numpy as np
import matplotlib.pyplot as plt
import time
# Load particle positioins
with open('//home//user//data.dat', 'r') as fp:
particles = []
for line in fp:
line = line.split()
if line:
line = [float(i) for i in line]
particles.append(line)
T = 100
numbParticles = 2
x, y = np.array([]), np.array([])
plt.ion()
plt.figure()
plt.scatter(x,y)
for t in range(T):
plt.clf()
for k in range(numbP):
x = np.append(x, particles[numbParticles*t+k][0])
y = np.append(y, particles[numbParticles*t+k][1])
plt.scatter(x,y)
plt.draw()
time.sleep(1)
x, y = np.array([]), np.array([])
python matplotlib
python matplotlib
asked Nov 18 '16 at 22:08
SamuelSamuel
7111125
7111125
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
The simplest, cleanest way to make an animation is to use the matplotlib.animation module.
Since a scatter plot returns a matplotlib.collections.PathCollection, the way to update it is to call its set_offsets method. You can pass it an array of shape (N, 2) or a list of N 2-tuples -- each 2-tuple being an (x,y) coordinate.
For example,
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
T = 100
numbParticles = 2
particles = np.random.random((T,numbParticles)).tolist()
x, y = np.array([]), np.array([])
def init():
pathcol.set_offsets([[], []])
return [pathcol]
def update(i, pathcol, particles):
pathcol.set_offsets(particles[i])
return [pathcol]
fig = plt.figure()
xs, ys = zip(*particles)
xmin, xmax = min(xs), max(xs)
ymin, ymax = min(ys), max(ys)
ax = plt.axes(xlim=(xmin, xmax), ylim=(ymin, ymax))
pathcol = plt.scatter([], [], s=100)
anim = animation.FuncAnimation(
fig, update, init_func=init, fargs=(pathcol, particles), interval=1000, frames=T,
blit=True, repeat=True)
plt.show()
1
Do I not need a loop? I do not see where I pass my list of numbers for every timestep. Can you please explain that?
– Samuel
Nov 18 '16 at 22:43
1
The loop resides in the call toFuncAnimation(). For every timestep (here every 1000 ms) the functionupdateis called with an incremented value ofi.
– ImportanceOfBeingErnest
Nov 19 '16 at 0:01
@ImportanceOfBeingErnest I do not see whereigets incremented. I would expect something likei=i+1.
– Samuel
Nov 19 '16 at 10:10
@Samuel As I said, the loop is insideFuncAnimation()so you don't see it. You can look at the source code if you like (actually there is no loop there, but an iterator), but you can also just accept that seen from the outsideFuncAnimation(fig, update, interval=1000, frames=100)will just call the functionupdateevery 1000 ms and incrementiby 1 up to the number given byframes.
– ImportanceOfBeingErnest
Nov 19 '16 at 10:46
1
set_offsetswas the key for me. Why can't pyplot have a centralised interface for setting data of elements :( ... likeset_data()
– Ciprian Tomoiagă
Aug 31 '18 at 14:54
add a comment |
I finally found a solution. You can do it simply by using this script. I tried to keep it simple:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Helps me to get the data from the file I want to plot
N = 0
# Load particle positioins
with open('//home//user//data.dat', 'r') as fp:
particles = []
for line in fp:
line = line.split()
particles.append(line)
# Create new Figure and an Axes which fills it.
fig = plt.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1], frameon=True)
border = 100
ax.set_xlim(-border, border), ax.set_xticks([])
ax.set_ylim(-border, border), ax.set_yticks([])
# particle data
p = 18 # number of particles
myPa = np.zeros(p, dtype=[('position', float, 2)])
# Construct the scatter which we will update during animation
scat = ax.scatter(myPa['position'][:, 0], myPa['position'][:, 1])
def update(frame_number):
# New positions
myPa['position'][:] = particles[N*p:N*p+p]
# Update the scatter collection, with the new colors, sizes and positions.
scat.set_offsets(myPa['position'])
increment()
def increment():
global N
N = N+1
# Construct the animation, using the update function as the animation director.
animation = FuncAnimation(fig, update, interval=20)
plt.show()
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40686697%2fpython-matplotlib-update-scatter%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
The simplest, cleanest way to make an animation is to use the matplotlib.animation module.
Since a scatter plot returns a matplotlib.collections.PathCollection, the way to update it is to call its set_offsets method. You can pass it an array of shape (N, 2) or a list of N 2-tuples -- each 2-tuple being an (x,y) coordinate.
For example,
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
T = 100
numbParticles = 2
particles = np.random.random((T,numbParticles)).tolist()
x, y = np.array([]), np.array([])
def init():
pathcol.set_offsets([[], []])
return [pathcol]
def update(i, pathcol, particles):
pathcol.set_offsets(particles[i])
return [pathcol]
fig = plt.figure()
xs, ys = zip(*particles)
xmin, xmax = min(xs), max(xs)
ymin, ymax = min(ys), max(ys)
ax = plt.axes(xlim=(xmin, xmax), ylim=(ymin, ymax))
pathcol = plt.scatter([], [], s=100)
anim = animation.FuncAnimation(
fig, update, init_func=init, fargs=(pathcol, particles), interval=1000, frames=T,
blit=True, repeat=True)
plt.show()
1
Do I not need a loop? I do not see where I pass my list of numbers for every timestep. Can you please explain that?
– Samuel
Nov 18 '16 at 22:43
1
The loop resides in the call toFuncAnimation(). For every timestep (here every 1000 ms) the functionupdateis called with an incremented value ofi.
– ImportanceOfBeingErnest
Nov 19 '16 at 0:01
@ImportanceOfBeingErnest I do not see whereigets incremented. I would expect something likei=i+1.
– Samuel
Nov 19 '16 at 10:10
@Samuel As I said, the loop is insideFuncAnimation()so you don't see it. You can look at the source code if you like (actually there is no loop there, but an iterator), but you can also just accept that seen from the outsideFuncAnimation(fig, update, interval=1000, frames=100)will just call the functionupdateevery 1000 ms and incrementiby 1 up to the number given byframes.
– ImportanceOfBeingErnest
Nov 19 '16 at 10:46
1
set_offsetswas the key for me. Why can't pyplot have a centralised interface for setting data of elements :( ... likeset_data()
– Ciprian Tomoiagă
Aug 31 '18 at 14:54
add a comment |
The simplest, cleanest way to make an animation is to use the matplotlib.animation module.
Since a scatter plot returns a matplotlib.collections.PathCollection, the way to update it is to call its set_offsets method. You can pass it an array of shape (N, 2) or a list of N 2-tuples -- each 2-tuple being an (x,y) coordinate.
For example,
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
T = 100
numbParticles = 2
particles = np.random.random((T,numbParticles)).tolist()
x, y = np.array([]), np.array([])
def init():
pathcol.set_offsets([[], []])
return [pathcol]
def update(i, pathcol, particles):
pathcol.set_offsets(particles[i])
return [pathcol]
fig = plt.figure()
xs, ys = zip(*particles)
xmin, xmax = min(xs), max(xs)
ymin, ymax = min(ys), max(ys)
ax = plt.axes(xlim=(xmin, xmax), ylim=(ymin, ymax))
pathcol = plt.scatter([], [], s=100)
anim = animation.FuncAnimation(
fig, update, init_func=init, fargs=(pathcol, particles), interval=1000, frames=T,
blit=True, repeat=True)
plt.show()
1
Do I not need a loop? I do not see where I pass my list of numbers for every timestep. Can you please explain that?
– Samuel
Nov 18 '16 at 22:43
1
The loop resides in the call toFuncAnimation(). For every timestep (here every 1000 ms) the functionupdateis called with an incremented value ofi.
– ImportanceOfBeingErnest
Nov 19 '16 at 0:01
@ImportanceOfBeingErnest I do not see whereigets incremented. I would expect something likei=i+1.
– Samuel
Nov 19 '16 at 10:10
@Samuel As I said, the loop is insideFuncAnimation()so you don't see it. You can look at the source code if you like (actually there is no loop there, but an iterator), but you can also just accept that seen from the outsideFuncAnimation(fig, update, interval=1000, frames=100)will just call the functionupdateevery 1000 ms and incrementiby 1 up to the number given byframes.
– ImportanceOfBeingErnest
Nov 19 '16 at 10:46
1
set_offsetswas the key for me. Why can't pyplot have a centralised interface for setting data of elements :( ... likeset_data()
– Ciprian Tomoiagă
Aug 31 '18 at 14:54
add a comment |
The simplest, cleanest way to make an animation is to use the matplotlib.animation module.
Since a scatter plot returns a matplotlib.collections.PathCollection, the way to update it is to call its set_offsets method. You can pass it an array of shape (N, 2) or a list of N 2-tuples -- each 2-tuple being an (x,y) coordinate.
For example,
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
T = 100
numbParticles = 2
particles = np.random.random((T,numbParticles)).tolist()
x, y = np.array([]), np.array([])
def init():
pathcol.set_offsets([[], []])
return [pathcol]
def update(i, pathcol, particles):
pathcol.set_offsets(particles[i])
return [pathcol]
fig = plt.figure()
xs, ys = zip(*particles)
xmin, xmax = min(xs), max(xs)
ymin, ymax = min(ys), max(ys)
ax = plt.axes(xlim=(xmin, xmax), ylim=(ymin, ymax))
pathcol = plt.scatter([], [], s=100)
anim = animation.FuncAnimation(
fig, update, init_func=init, fargs=(pathcol, particles), interval=1000, frames=T,
blit=True, repeat=True)
plt.show()
The simplest, cleanest way to make an animation is to use the matplotlib.animation module.
Since a scatter plot returns a matplotlib.collections.PathCollection, the way to update it is to call its set_offsets method. You can pass it an array of shape (N, 2) or a list of N 2-tuples -- each 2-tuple being an (x,y) coordinate.
For example,
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
T = 100
numbParticles = 2
particles = np.random.random((T,numbParticles)).tolist()
x, y = np.array([]), np.array([])
def init():
pathcol.set_offsets([[], []])
return [pathcol]
def update(i, pathcol, particles):
pathcol.set_offsets(particles[i])
return [pathcol]
fig = plt.figure()
xs, ys = zip(*particles)
xmin, xmax = min(xs), max(xs)
ymin, ymax = min(ys), max(ys)
ax = plt.axes(xlim=(xmin, xmax), ylim=(ymin, ymax))
pathcol = plt.scatter([], [], s=100)
anim = animation.FuncAnimation(
fig, update, init_func=init, fargs=(pathcol, particles), interval=1000, frames=T,
blit=True, repeat=True)
plt.show()
answered Nov 18 '16 at 22:30
unutbuunutbu
574k10912431287
574k10912431287
1
Do I not need a loop? I do not see where I pass my list of numbers for every timestep. Can you please explain that?
– Samuel
Nov 18 '16 at 22:43
1
The loop resides in the call toFuncAnimation(). For every timestep (here every 1000 ms) the functionupdateis called with an incremented value ofi.
– ImportanceOfBeingErnest
Nov 19 '16 at 0:01
@ImportanceOfBeingErnest I do not see whereigets incremented. I would expect something likei=i+1.
– Samuel
Nov 19 '16 at 10:10
@Samuel As I said, the loop is insideFuncAnimation()so you don't see it. You can look at the source code if you like (actually there is no loop there, but an iterator), but you can also just accept that seen from the outsideFuncAnimation(fig, update, interval=1000, frames=100)will just call the functionupdateevery 1000 ms and incrementiby 1 up to the number given byframes.
– ImportanceOfBeingErnest
Nov 19 '16 at 10:46
1
set_offsetswas the key for me. Why can't pyplot have a centralised interface for setting data of elements :( ... likeset_data()
– Ciprian Tomoiagă
Aug 31 '18 at 14:54
add a comment |
1
Do I not need a loop? I do not see where I pass my list of numbers for every timestep. Can you please explain that?
– Samuel
Nov 18 '16 at 22:43
1
The loop resides in the call toFuncAnimation(). For every timestep (here every 1000 ms) the functionupdateis called with an incremented value ofi.
– ImportanceOfBeingErnest
Nov 19 '16 at 0:01
@ImportanceOfBeingErnest I do not see whereigets incremented. I would expect something likei=i+1.
– Samuel
Nov 19 '16 at 10:10
@Samuel As I said, the loop is insideFuncAnimation()so you don't see it. You can look at the source code if you like (actually there is no loop there, but an iterator), but you can also just accept that seen from the outsideFuncAnimation(fig, update, interval=1000, frames=100)will just call the functionupdateevery 1000 ms and incrementiby 1 up to the number given byframes.
– ImportanceOfBeingErnest
Nov 19 '16 at 10:46
1
set_offsetswas the key for me. Why can't pyplot have a centralised interface for setting data of elements :( ... likeset_data()
– Ciprian Tomoiagă
Aug 31 '18 at 14:54
1
1
Do I not need a loop? I do not see where I pass my list of numbers for every timestep. Can you please explain that?
– Samuel
Nov 18 '16 at 22:43
Do I not need a loop? I do not see where I pass my list of numbers for every timestep. Can you please explain that?
– Samuel
Nov 18 '16 at 22:43
1
1
The loop resides in the call to
FuncAnimation(). For every timestep (here every 1000 ms) the function update is called with an incremented value of i.– ImportanceOfBeingErnest
Nov 19 '16 at 0:01
The loop resides in the call to
FuncAnimation(). For every timestep (here every 1000 ms) the function update is called with an incremented value of i.– ImportanceOfBeingErnest
Nov 19 '16 at 0:01
@ImportanceOfBeingErnest I do not see where
i gets incremented. I would expect something like i=i+1.– Samuel
Nov 19 '16 at 10:10
@ImportanceOfBeingErnest I do not see where
i gets incremented. I would expect something like i=i+1.– Samuel
Nov 19 '16 at 10:10
@Samuel As I said, the loop is inside
FuncAnimation() so you don't see it. You can look at the source code if you like (actually there is no loop there, but an iterator), but you can also just accept that seen from the outside FuncAnimation(fig, update, interval=1000, frames=100) will just call the function update every 1000 ms and increment i by 1 up to the number given by frames.– ImportanceOfBeingErnest
Nov 19 '16 at 10:46
@Samuel As I said, the loop is inside
FuncAnimation() so you don't see it. You can look at the source code if you like (actually there is no loop there, but an iterator), but you can also just accept that seen from the outside FuncAnimation(fig, update, interval=1000, frames=100) will just call the function update every 1000 ms and increment i by 1 up to the number given by frames.– ImportanceOfBeingErnest
Nov 19 '16 at 10:46
1
1
set_offsets was the key for me. Why can't pyplot have a centralised interface for setting data of elements :( ... like set_data()– Ciprian Tomoiagă
Aug 31 '18 at 14:54
set_offsets was the key for me. Why can't pyplot have a centralised interface for setting data of elements :( ... like set_data()– Ciprian Tomoiagă
Aug 31 '18 at 14:54
add a comment |
I finally found a solution. You can do it simply by using this script. I tried to keep it simple:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Helps me to get the data from the file I want to plot
N = 0
# Load particle positioins
with open('//home//user//data.dat', 'r') as fp:
particles = []
for line in fp:
line = line.split()
particles.append(line)
# Create new Figure and an Axes which fills it.
fig = plt.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1], frameon=True)
border = 100
ax.set_xlim(-border, border), ax.set_xticks([])
ax.set_ylim(-border, border), ax.set_yticks([])
# particle data
p = 18 # number of particles
myPa = np.zeros(p, dtype=[('position', float, 2)])
# Construct the scatter which we will update during animation
scat = ax.scatter(myPa['position'][:, 0], myPa['position'][:, 1])
def update(frame_number):
# New positions
myPa['position'][:] = particles[N*p:N*p+p]
# Update the scatter collection, with the new colors, sizes and positions.
scat.set_offsets(myPa['position'])
increment()
def increment():
global N
N = N+1
# Construct the animation, using the update function as the animation director.
animation = FuncAnimation(fig, update, interval=20)
plt.show()
add a comment |
I finally found a solution. You can do it simply by using this script. I tried to keep it simple:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Helps me to get the data from the file I want to plot
N = 0
# Load particle positioins
with open('//home//user//data.dat', 'r') as fp:
particles = []
for line in fp:
line = line.split()
particles.append(line)
# Create new Figure and an Axes which fills it.
fig = plt.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1], frameon=True)
border = 100
ax.set_xlim(-border, border), ax.set_xticks([])
ax.set_ylim(-border, border), ax.set_yticks([])
# particle data
p = 18 # number of particles
myPa = np.zeros(p, dtype=[('position', float, 2)])
# Construct the scatter which we will update during animation
scat = ax.scatter(myPa['position'][:, 0], myPa['position'][:, 1])
def update(frame_number):
# New positions
myPa['position'][:] = particles[N*p:N*p+p]
# Update the scatter collection, with the new colors, sizes and positions.
scat.set_offsets(myPa['position'])
increment()
def increment():
global N
N = N+1
# Construct the animation, using the update function as the animation director.
animation = FuncAnimation(fig, update, interval=20)
plt.show()
add a comment |
I finally found a solution. You can do it simply by using this script. I tried to keep it simple:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Helps me to get the data from the file I want to plot
N = 0
# Load particle positioins
with open('//home//user//data.dat', 'r') as fp:
particles = []
for line in fp:
line = line.split()
particles.append(line)
# Create new Figure and an Axes which fills it.
fig = plt.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1], frameon=True)
border = 100
ax.set_xlim(-border, border), ax.set_xticks([])
ax.set_ylim(-border, border), ax.set_yticks([])
# particle data
p = 18 # number of particles
myPa = np.zeros(p, dtype=[('position', float, 2)])
# Construct the scatter which we will update during animation
scat = ax.scatter(myPa['position'][:, 0], myPa['position'][:, 1])
def update(frame_number):
# New positions
myPa['position'][:] = particles[N*p:N*p+p]
# Update the scatter collection, with the new colors, sizes and positions.
scat.set_offsets(myPa['position'])
increment()
def increment():
global N
N = N+1
# Construct the animation, using the update function as the animation director.
animation = FuncAnimation(fig, update, interval=20)
plt.show()
I finally found a solution. You can do it simply by using this script. I tried to keep it simple:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Helps me to get the data from the file I want to plot
N = 0
# Load particle positioins
with open('//home//user//data.dat', 'r') as fp:
particles = []
for line in fp:
line = line.split()
particles.append(line)
# Create new Figure and an Axes which fills it.
fig = plt.figure(figsize=(7, 7))
ax = fig.add_axes([0, 0, 1, 1], frameon=True)
border = 100
ax.set_xlim(-border, border), ax.set_xticks([])
ax.set_ylim(-border, border), ax.set_yticks([])
# particle data
p = 18 # number of particles
myPa = np.zeros(p, dtype=[('position', float, 2)])
# Construct the scatter which we will update during animation
scat = ax.scatter(myPa['position'][:, 0], myPa['position'][:, 1])
def update(frame_number):
# New positions
myPa['position'][:] = particles[N*p:N*p+p]
# Update the scatter collection, with the new colors, sizes and positions.
scat.set_offsets(myPa['position'])
increment()
def increment():
global N
N = N+1
# Construct the animation, using the update function as the animation director.
animation = FuncAnimation(fig, update, interval=20)
plt.show()
edited Nov 19 '16 at 10:09
answered Nov 19 '16 at 0:22
SamuelSamuel
7111125
7111125
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40686697%2fpython-matplotlib-update-scatter%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown