Adding a second plot to an existing matplotlib chart - python

I would like to have a function that adds plots to an existing chart when called. Right now my empty plot shows, but called the function never seems to happen as it waits until I close the chart window. The program then ends without reopening the chart window.
import numpy as np
import matplotlib.pyplot as plt
import time
fig, ax = plt.subplots()
plt.show()
def plotting(slope, intercept):
x_vals = np.array(ax.get_xlim())
y_vals = intercept + slope * x_vals
ax.plot(x_vals, y_vals, '-')
plt.show()
plotting(10,39)
time.sleep(1)
plotting(5,39)

plt.show() is meant to be called once at the end of the script. It will block until the plotting window is closed.
You may use interactive mode (plt.ion()) and draw the plot at intermediate steps (plt.draw()). To obtain a pause, don't use time.sleep() because it'll let the application sleep literally (possibly leading to freezed windows). Instead, use plt.pause(). At the end, you may turn interactive mode off again (plt.ioff()) and finally call plt.show() in order to let the plot stay open.
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
fig, ax = plt.subplots()
def plotting(slope, intercept):
x_vals = np.array(ax.get_xlim())
y_vals = intercept + slope * x_vals
ax.plot(x_vals, y_vals, '-')
plt.draw()
plotting(10,39)
plt.pause(1)
plotting(5,39)
plt.ioff()
plt.show()

Send the optional keyword argument block=False to plt.show().
Explanation: the plot window blocks the program from continuing. Sending this argument will allow the program to continue.
Notice that if you only use that argument and the program ends, then the plot window is closed. Therefore you might want to call plt.show(block=True) or plt.waitforbuttonpress() at the end of the program.
Personally I would go for adding a block argument for your own function:
def plotting(slope, intercept, block=True):
x_vals = np.array(ax.get_xlim())
y_vals = intercept + slope * x_vals
ax.plot(x_vals, y_vals, '-')
plt.show(block=block)
plotting(10,39,False)
time.sleep(1)
plotting(5,39)

Related

Dynamically update plot Matplotlib Python (for unsteady heat diffusion)

I am new to python and trying to do what have been doing in MATLAB for so long. My current challenge is to dynamically update a plot without drawing a new figure in a for or while loop. I am aware there are similar questions and answers but most of them are too complicated and I believe it should be easier.
I got the example from here
https://pythonspot.com/matplotlib-update-plot/
But I can't see the figure, no error, no nothing. I added two lines just to see if I can see the static plot and I can.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10*np.pi, 100)
y = np.sin(x)
# This is just a test just to see if I can see the plot window
plt.plot(x, y)
plt.show()
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'b-')
for phase in np.linspace(0, 10*np.pi, 100):
line1.set_ydata(np.sin(0.5 * x + phase))
fig.canvas.draw()
Any idea why I can't see the dynamic plot?
Thank you
Erdem
try to add plt.pause(0.0001) inside the loop after plt.show(block=False), and a final plt.show() outside the loop. This should work fine with plt.ion(); ref to some older answers Plot one figure at a time without closing old figure (matplotlib)

MatPlotLib with ion() does not show window

If I run the following code:
import matplotlib.pyplot as plt
import numpy as np
#plt.ion()
while True:
print('loop')
x = range(10)
y = np.random.rand(10)
plt.scatter(x, y)
plt.show()
Then I see a scatter plot displayed on my screen. Then each time I close the window for the plot, it displays a new plot with new data.
However, if I uncomment the line plt.ion(), nothing is displayed at all. There is no window created, and the program just continues through the loop, printing out 'loop'.
I want to be able to display a graph, and then return to the code automatically, with the graph still displayed. How can I do this?
If you want to plot on top of the same figure window, rather than generating a new window at every iteration the following will work:
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
fig, ax = plt.subplots(1, 1)
while True:
# If wanting to see an "animation" of points added, add a pause to allow the plotting to take place
plt.pause(1)
x = range(10)
y = np.random.rand(10)
ax.scatter(x, y)
The result you see will depend on the which matplotlib backend you are using. If you're wanting to see the new points being added you should use Qt4 or Qt5

Animating a function where function parameters change with time using FuncAnimation

I am trying to animate a one-dimensional function where the function inputs are same but function parameters are changing with time. The function I am trying to animate is
f(x)=sin(a* pi * x)/(b*x)+ (x-1)^4
Here the data to be plotted is same, but a, b are changing with every update.I am using python and matplotlib library. My initial attempt is as follows:
fig,ax = plt.subplots()
line, = ax.plot([],[])
def animate(i,func_params):
x = np.linspace(-0.5,2.5,num = 200)
a=func_params[i][0]
b=func_params[i][1]
y=np.sin(a*math.pi*x)/b*x + (x-1)**4
line.set_xdata(x)
line.set_ydata(y)
return line,
ani = animation.FuncAnimation(fig,animate,frames=len(visualize_pop),fargs=(visualize_func,),interval = 100,blit=True)
plt.show()
The above code is not plotting anything.
EDIT: Updated code based on comment.
Your problem is that with plot([],[]) you give matplotlib no data and therefore no way do determine the limits of the axes. Therefore it uses some default values which are way out of the range of the data you actually want to plot. Therefore you have two choices:
1) Set the limits to some values that will contain all your plotted data for all cases,
e.g.
ax.set_xlim([-0.5,2.5])
ax.set_ylim([-2,6])
2) Let ax compute the limits automatically each frame and re-scale the plot see here using these two commands within your animate function (note that this option only works correctly if you turn blitting off):
ax.relim()
ax.autoscale_view()
Here still a completely working version of your code (the commands for solution (1) are commented out and I changed some of the notations):
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
fig,ax = plt.subplots()
x = np.linspace(-0.5,2.5,num = 200)
line, = ax.plot([],[])
#ax.set_xlim([-0.5,2.5])
#ax.set_ylim([-2,6])
##assuming some parameters, because none were given by the OP:
N = 20
func_args = np.array([np.linspace(1,2,N), np.linspace(2,1,N)])
def animate(i,func_params):
a=func_params[0,i]
b=func_params[1,i]
y=np.sin(a*np.pi*x)/b*x + (x-1)**4
line.set_xdata(x)
line.set_ydata(y)
ax.relim()
ax.autoscale_view()
return line, ax
##blit=True will not update the axes labels correctly
ani = FuncAnimation(
fig,animate,frames=N, fargs=(func_args,),interval = 100 #, blit=True
)
plt.show()

Matplotlib needs careful timing? (Or is there a flag to show plotting is done?)

The following code does not work as expected:
import matplotlib.pyplot as plt
plt.plot(range(100000), '.')
plt.draw()
ax = plt.gca()
lblx = ax.get_xticklabels()
lblx[1]._text = 'hello!'
ax.set_xticklabels(lblx)
plt.draw()
plt.show()
I'm getting the following figure:
I imagine that the reason is that the automatic xticklabels did not have time to be fully created when get_xticklabels() was called. And indeed, by adding plt.pause(1)
import matplotlib.pyplot as plt
plt.plot(range(100000), '.')
plt.draw()
plt.pause(1)
ax = plt.gca()
lblx = ax.get_xticklabels()
lblx[1]._text = 'hello!'
ax.set_xticklabels(lblx)
plt.draw()
plt.show()
would give the expected
I'm not very happy with this state (having to manually insert delays). And my main concern is: How can I know how much time I need to wait? Surely it depends on number of figure elements, machine strength, etc..
So my question is: Is there some flag to know that matplotlib has finished drawing all the elements? Or is there a better way to do what I'm doing?
First it should be noted that you may make an arbitrarily short pause
plt.pause(1e-18)
The issue here is that plt.draw() calls plt.gcf().canvas.draw_idle(). This means that the figure is drawn at some arbitrary point when there is time to do it - hence the _idle.
Instead you would probably want to draw the figure at the specific point in the code you need.
plt.gcf().canvas.draw()
Full code:
import matplotlib.pyplot as plt
plt.plot(range(100000), '.')
plt.gcf().canvas.draw()
ax = plt.gca()
lblx = ax.get_xticklabels()
lblx[1]._text = 'hello!'
ax.set_xticklabels(lblx)
plt.show()

Plotting a continuous stream of data with MatPlotLib

I want to use MatPlotLib to plot a graph, where the plot changes over time. At every time step, an additional data point will be added to the plot. However, there should only be one graph displayed, whose appearance evolves over time.
In my test example, the plot is a simple linear plot (y = x). Here is what I have tried:
for i in range(100):
x = range(i)
y = range(i)
plt.plot(x, y)
plt.ion()
plt.show()
time.sleep(1)
However, what happens here is that multiple windows are created, so that by the end of the loop I have 100 windows. Also, I have noticed that for the most recent window, it is just a white window, and the plot only appears on the next step.
So, my two questions are:
1) How can I change my code so that only a single window is displayed, whose contents changes over time?
2) How can I change my code so that for the most recent timestep, the plot is actually displayed on the window, rather than it only displaying a white window?
Thanks!
(1)
You can set plt.ion() at the beginning and plot all graphs to the same window. Within the loop use plt.draw() to show the graph and plt.pause(t) to make a pause. Note that t can be very small, but the command needs to be there for the animation to work on most backends.
You might want to clear the axes before plotting new content using plt.gca().cla().
import matplotlib.pyplot as plt
plt.ion()
for i in range(100):
x = range(i)
y = range(i)
# plt.gca().cla() # optionally clear axes
plt.plot(x, y)
plt.title(str(i))
plt.draw()
plt.pause(0.1)
plt.show(block=True) # block=True lets the window stay open at the end of the animation.
Alternatively to this very simple approach, use any of the examples for animations provided in http://matplotlib.org/examples/animation/index.html
(2)
In order to get each plot in a new window, use plt.figure() and remove plt.ion(). Also only show the windows at the end:
import matplotlib.pyplot as plt
for i in range(100):
x = range(i)
y = range(i)
plt.figure()
plt.plot(x, y)
plt.title(str(i))
plt.show()
Note that you might find that in both cases the first plot is empty simply because for i=0, range(i) == [] is an empty list without any points. Even for i=1 there is only one point being plotted, but of course no line can connect a single point with itself.
I think the best way is to create one line plot and then update data in it. Then you will have single window and single graph that will continuously update.
import matplotlib.pyplot as plt
plt.ion()
fig = plt.figure(figsize=(16,8))
axes = fig.add_subplot(111)
data_plot=plt.plot(0,0)
line, = axes.plot([],[])
for i in range(100):
x = range(i)
y = range(i)
line.set_ydata(y)
line.set_xdata(x)
if len(y)>0:
axes.set_ylim(min(y),max(y)+1) # +1 to avoid singular transformation warning
axes.set_xlim(min(x),max(x)+1)
plt.title(str(i))
plt.draw()
plt.pause(0.1)
plt.show(block=True)

Categories

Resources