0

I want to do a standard matplotlib animation with the twist that I want different groups as a "single" line, not plotting 10 groups sharing same x axis. For context, I am trying to chart the sentiment of 10 books in a series, and want to color-code the lines for each book. All the searches I've found for animating a line seem to be that you must start from x = 0 to current x, which makes it difficult to assign the correct coloring label.

For example, taking Animating "growing" line plot in Python/Matplotlib this example. Say I want to break x in [0,10) as one group, x in [10,20) as group 2, etc. How would I do this in an animated fashion?

I'm trying to get the animated version:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as ani

%matplotlib notebook

import matplotlib.colors as mcolors
colors = list(mcolors.XKCD_COLORS.keys())[0:10]


x = np.linspace(0, 10, 100)
y = np.sin(x)

fig, ax = plt.subplots()
line, = ax.plot(x, y, color='k')

def update(num, x, y, line):
    line.set_data(x[:num], y[:num])
    line.axes.axis([0, 10, 0, 1])
    return line,

anim = ani.FuncAnimation(fig, update, len(x), fargs=[x, y, line],
                              interval=25, blit=True)
plt.show()

to look like this, but animated with each segment a color:

plt.figure()
x_beg = 0
for i in range(1,11):
    plt.plot(x[x_beg:(x_beg + i * 10)],
             y[x_beg:(x_beg + i * 10)],
             label=i)
    x_beg += i * 10
    
plt.legend(loc='best', fontsize=15)
plt.show()    

enter image description here

  • Welcome to Stack Overflow! Please take a moment to read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask). You need to provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) that includes a toy dataset (refer to [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples)). – Diziet Asahi Jan 02 '21 at 06:17
  • In your case, please provide the code that would generate the plot at the end of the animation, or at the very least your data and a mockup of what that plot should look like and what parts you want animated – Diziet Asahi Jan 02 '21 at 06:18
  • Posted! Updated post with code – randomcat123x Jan 02 '21 at 07:06

1 Answers1

0

The answer to this I came up with is creating X groups of padded lines that I want to chart, with nan filled in for values that I don't want to display, then animating all lines simultaneously