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