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;








0















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









share|improve this question




























    0















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









    share|improve this question
























      0












      0








      0








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









      share|improve this question














      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






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 18 '16 at 22:08









      SamuelSamuel

      7111125




      7111125






















          2 Answers
          2






          active

          oldest

          votes


















          3














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





          share|improve this answer


















          • 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 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











          • @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





            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


















          0














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





          share|improve this answer

























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



            );













            draft saved

            draft discarded


















            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









            3














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





            share|improve this answer


















            • 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 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











            • @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





              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















            3














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





            share|improve this answer


















            • 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 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











            • @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





              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













            3












            3








            3







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





            share|improve this answer













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






            share|improve this answer












            share|improve this answer



            share|improve this answer










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











            • @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





              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












            • 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 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











            • @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





              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







            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













            0














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





            share|improve this answer





























              0














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





              share|improve this answer



























                0












                0








                0







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





                share|improve this answer















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






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 19 '16 at 10:09

























                answered Nov 19 '16 at 0:22









                SamuelSamuel

                7111125




                7111125



























                    draft saved

                    draft discarded
















































                    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.




                    draft saved


                    draft discarded














                    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





















































                    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







                    Popular posts from this blog

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                    155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해