Dynamically drawing n graphs
I am writing a measurement program and matplotlib is used to display the measurement values as they are received. I figured out how to do this for one plot, i.e.
x=[0,1,2] y=[3,5,7] set_xdata(x) set_ydata(y)
Every time x and y change, I call set_xdata
and set_ydata
and update the graph.
However, I want to dynamically plot the n
y values against a single x value, i.e.
x=[0,1,2]
y=[[3,5,7],[4,6,8],[5,7,9]]
Can this be done knowing n
(number of y-plots)?
EDIT:
I am interested in two things:
- How to simply refresh the data of the multiset, and not completely redraw the graph every time the data changes?
- Does matplotlib support multiple Y data to display single X data?
source to share
In short: you need to create an instance Line2D
for each "plot". And a little more verbose:
-
As you did it with one line, you can also do the same with multiple lines:
import matplotlib.pyplot as plt # initial values x = [0,1,2] y = [[3,5,7],[4,6,8],[5,7,9]] # create the line instances and store them in a list line_objects = list() for yi in y: line_objects.extend(plt.plot(x, yi)) # new values with which we want to update the plot x = [1,2,3] y = [[4,6,8],[5,7,9],[6,8,0]] # update the y values dynamically (without recreating the plot) for yi, line_object in zip(y, line_objects): line_object.set_xdata(x) line_object.set_ydata(yi)
-
Not really. However, you can create mulitple objects with a
Line2D
single callplot
:line_objects = plt.plot(x, y[0], x, y[1], x, y[2])
This is why it
plot
always returns a list.
EDIT:
If you need to do this frequently, helper functions can help:
eg:.
def plot_multi_y(x, ys, ax=None, **kwargs):
if ax is None:
ax = plt.gca()
return [ax.plot(x, y, **kwargs)[0] for y in ys]
def update_multi_y(line_objects, x, ys):
for y, line_object in zip(ys, line_objects):
line_object.set_xdata(x)
line_object.set_ydata(y)
Then you can simply use:
# create the lines
line_objects = plot_multi_y(x, y)
#update the lines
update_multi_y(line_objects, x, y)
source to share