Matplotlib figures not changing interactively - Canopy Ipython - python

I am trying to use the ipython in canopy with matplotlib to prepare graphs (backend set to qt). I wrote the following code line by line int the terminal
import matplotlib.pyplot as plt
fig = plt.figure()
s = fig.add_subplot(1,1,1)
after the second line I can see the figure being made. However after the third line I do not see the sub plot being created. However If I print fig, the sub-plot is can be seen both inline and in the figure window created. This sub-plot also magically appears if I try to zoom. Similar thing happens every time i plot something on the figure. The old version is displayed till I either print the figure or if i try to modify the view using the GUI tools. This is really annoying. It would be great if someone could tell me where the problem is.
Edit: Tried using fig.show() which does not work. Also when I use the plt.plot() directly, there seems to be no problem. The problem comes only when i use fig or any of its subplots

type:
fig.show() when you need to update it.

you should try using fig.canvas.draw() instead of using fig.show() when it comes to interactive plots.
import matplotlib.pyplot as plt
fig = plt.figure()
fig.show()
## should show an empty figure ##
s = fig.add_subplot(1,1,1)
fig.show()
## things stay unchanged ##
fig.canvas.draw()
## things should be OK now ##

Related

How to make Spyder wait until matplotlib plot has been constructed

Coming from a R background I am now moving on to Python and would like to learn Spyder 4 as a next tool alongside RStudio for data analysis. I am running into a problem however trying to learn matplotlib.
Having this code:
import matplotlib.pyplot as plt
x = [1,2,3,4,5,6,7,8,5,4,3,3,2,4,5,6]
y = [5,5,6,7,8,3,4,5,6,7,8,6,5,4,3,2]
plt.xlabel('x-as')
plt.ylabel('y-as')
plt.title('My title')
plt.legend()
plt.scatter(x, y, label = 'test')
plt.show()
This will not wait for the call to plt.show(), but instead plot a graph for each of the calls to a matplotlib functions, in the plot viewer section of the IDE.
How would I make Spyder 4 wait untill I actually want it to draw the graph?
You want to put fig = plt.figure() before the rest of the plotting lines. Also, you want to put plt.legend() after the scatter function so that the label shows.

matplotlib.pyplot.show() in PyCharm moves my axes! How can I prevent this?

When I create a figure in matplot lib and render that figure in PyCharm with matplotlib.pyplot.show(), the figure moves!
This does not occur show()ing outside of PyCharm.
import matplotlib.pyplot as plt
def axes_position_test():
"""Witness change in position after plt.show()."""
fig = plt.figure()
ax1 = fig.add_subplot(111)
# original position
print(ax1.get_position())
plt.show()
# position has changed
print(ax1.get_position())
axes_position_test()
# output
# Bbox(x0=0.125, y0=0.10999999999999999, x1=0.9, y1=0.88)
# Bbox(x0=0.07300347222222223, y0=0.08067129629629632, x1=0.959375, y1=0.9572916666666668)
I cannot reproduce the problem - the code results in an error for me running matplotlib 3.0.2. Maybe a different version is in use?
In any case, to generally answer this:
Positions may change over time, especially if the figure is shown inside a GUI which may itself (slightly) change the figure size.
The question is not really clear about the ultimate goal, but as I interprete it, the aim is to have two axes on top of each other. That is easily accomplished via
fig = plt.figure()
ax1 = fig.add_subplot(111, label="first axes")
ax2 = fig.add_subplot(111, label="second axes")
More sophisticated geometries can be made with gridspec, always using add_subplot to add the subplot.
Edit from OP: As revealed in comments, the PyCharm renderer, interagg, is the problem. Disabling interagg (Settings > Tools > Python Scientific > uncheck "show plots") corrects the problem.

Change style in one Matplotlib Figure when working with several Figures simultaneously

Let's say I have 2 Matplotlib Figures at the same time that are updated in a for loop. One of the Figures (let's say fig0 has images, while fig1 is a line plot). I would like fig0 to have the standard Matplotlib style while in fig1 I would like to set plt.style.use('ggplot') for fig1.
So far I have tried this:
plt.style.use('ggplot')
fig0 = plt.figure(0)
fig1 = plt.figure(1)
for i in range(10):
# print stuff in both figures
But this sets ggplot style in both Figures (as expected). I could not find the way to separately set style in each Figure.
This would solve it, except for the loop.
import matplotlib.pyplot as plt
with plt.style.context('ggplot'):
plt.figure(0)
plt.plot([3,2,1])
with plt.style.context('default'):
plt.figure(1)
plt.plot([1,2,3])
plt.show()
You'd probably be better off without the loop anyway... as long the loop isn't absolutely necessary for some reason. Just keep whatever you're adding to the plots in the loop in lists and modify the example above.

How to show matplotlib plot from a figure object

My code contains the following lines:
from matplotlib.figure import Figure
figure = Figure(figsize=(10, 5), dpi=dpi)
How can I get matplotlib to show this figure? I also show it embedded in tkinter, which workes fine. However I would also be able to show it in the standard matplotlib window. But I can't for the life of me get it to work.
According to AttributeError while trying to load the pickled matplotlib figure, a simple workaround is:
fig = plt.Figure(...)
......
managed_fig = plt.figure(...)
canvas_manager = managed_fig.canvas.manager
canvas_manager.canvas.figure = fig
fig.set_canvas(canvas_manager.canvas)
Note that I encountered "'Figure' object has no attribute '_original_dpi'" in my environment. Not sure if it's some compatibility issue between my PyPlot and the PyQt5. Just did a hack:
fig._original_dpi = 60
to get around this. Not sure if there are any better solutions.
I usually use matplotlib's pyplot for immediate generation (or produce images in jupyter notebooks). This would look like the following:
import matplotlib.pyplot as plt
figure = plt.figure(figsize=(10, 5), dpi=dpi)
plt.show()
This shows the (blank) figure as desired.

How can I show figures separately in matplotlib?

Say that I have two figures in matplotlib, with one plot per figure:
import matplotlib.pyplot as plt
f1 = plt.figure()
plt.plot(range(0,10))
f2 = plt.figure()
plt.plot(range(10,20))
Then I show both in one shot
plt.show()
Is there a way to show them separately, i.e. to show just f1?
Or better: how can I manage the figures separately like in the following 'wishful' code (that doesn't work):
f1 = plt.figure()
f1.plot(range(0,10))
f1.show()
Sure. Add an Axes using add_subplot. (Edited import.) (Edited show.)
import matplotlib.pyplot as plt
f1 = plt.figure()
f2 = plt.figure()
ax1 = f1.add_subplot(111)
ax1.plot(range(0,10))
ax2 = f2.add_subplot(111)
ax2.plot(range(10,20))
plt.show()
Alternatively, use add_axes.
ax1 = f1.add_axes([0.1,0.1,0.8,0.8])
ax1.plot(range(0,10))
ax2 = f2.add_axes([0.1,0.1,0.8,0.8])
ax2.plot(range(10,20))
With Matplotlib prior to version 1.0.1, show() should only be called once per program, even if it seems to work within certain environments (some backends, on some platforms, etc.).
The relevant drawing function is actually draw():
import matplotlib.pyplot as plt
plt.plot(range(10)) # Creates the plot. No need to save the current figure.
plt.draw() # Draws, but does not block
raw_input() # This shows the first figure "separately" (by waiting for "enter").
plt.figure() # New window, if needed. No need to save it, as pyplot uses the concept of current figure
plt.plot(range(10, 20))
plt.draw()
# raw_input() # If you need to wait here too...
# (...)
# Only at the end of your program:
plt.show() # blocks
It is important to recognize that show() is an infinite loop, designed to handle events in the various figures (resize, etc.). Note that in principle, the calls to draw() are optional if you call matplotlib.ion() at the beginning of your script (I have seen this fail on some platforms and backends, though).
I don't think that Matplotlib offers a mechanism for creating a figure and optionally displaying it; this means that all figures created with figure() will be displayed. If you only need to sequentially display separate figures (either in the same window or not), you can do like in the above code.
Now, the above solution might be sufficient in simple cases, and for some Matplotlib backends. Some backends are nice enough to let you interact with the first figure even though you have not called show(). But, as far as I understand, they do not have to be nice. The most robust approach would be to launch each figure drawing in a separate thread, with a final show() in each thread. I believe that this is essentially what IPython does.
The above code should be sufficient most of the time.
PS: now, with Matplotlib version 1.0.1+, show() can be called multiple times (with most backends).
I think I am a bit late to the party but...
In my opinion, what you need is the object oriented API of matplotlib. In matplotlib 1.4.2 and using IPython 2.4.1 with Qt4Agg backend, I can do the following:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1) # Creates figure fig and add an axes, ax.
fig2, ax2 = plt.subplots(1) # Another figure
ax.plot(range(20)) #Add a straight line to the axes of the first figure.
ax2.plot(range(100)) #Add a straight line to the axes of the first figure.
fig.show() #Only shows figure 1 and removes it from the "current" stack.
fig2.show() #Only shows figure 2 and removes it from the "current" stack.
plt.show() #Does not show anything, because there is nothing in the "current" stack.
fig.show() # Shows figure 1 again. You can show it as many times as you want.
In this case plt.show() shows anything in the "current" stack. You can specify figure.show() ONLY if you are using a GUI backend (e.g. Qt4Agg). Otherwise, I think you will need to really dig down into the guts of matplotlib to monkeypatch a solution.
Remember that most (all?) plt.* functions are just shortcuts and aliases for figure and axes methods. They are very useful for sequential programing, but you will find blocking walls very soon if you plan to use them in a more complex way.
Perhaps you need to read about interactive usage of Matplotlib. However, if you are going to build an app, you should be using the API and embedding the figures in the windows of your chosen GUI toolkit (see examples/embedding_in_tk.py, etc).
None of the above solutions seems to work in my case, with matplotlib 3.1.0 and Python 3.7.3. Either both the figures show up on calling show() or none show up in different answers posted above.
Building upon #Ivan's answer, and taking hint from here, the following seemed to work well for me:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1) # Creates figure fig and add an axes, ax.
fig2, ax2 = plt.subplots(1) # Another figure
ax.plot(range(20)) #Add a straight line to the axes of the first figure.
ax2.plot(range(100)) #Add a straight line to the axes of the first figure.
# plt.close(fig) # For not showing fig
plt.close(fig2) # For not showing fig2
plt.show()
As #arpanmangal, the solutions above do not work for me (matplotlib 3.0.3, python 3.5.2).
It seems that using .show() in a figure, e.g., figure.show(), is not recommended, because this method does not manage a GUI event loop and therefore the figure is just shown briefly. (See figure.show() documentation). However, I do not find any another way to show only a figure.
In my solution I get to prevent the figure for instantly closing by using click events. We do not have to close the figure — closing the figure deletes it.
I present two options:
- waitforbuttonpress(timeout=-1) will close the figure window when clicking on the figure, so we cannot use some window functions like zooming.
- ginput(n=-1,show_clicks=False) will wait until we close the window, but it releases an error :-.
Example:
import matplotlib.pyplot as plt
fig1, ax1 = plt.subplots(1) # Creates figure fig1 and add an axes, ax1
fig2, ax2 = plt.subplots(1) # Another figure fig2 and add an axes, ax2
ax1.plot(range(20),c='red') #Add a red straight line to the axes of fig1.
ax2.plot(range(100),c='blue') #Add a blue straight line to the axes of fig2.
#Option1: This command will hold the window of fig2 open until you click on the figure
fig2.waitforbuttonpress(timeout=-1) #Alternatively, use fig1
#Option2: This command will hold the window open until you close the window, but
#it releases an error.
#fig2.ginput(n=-1,show_clicks=False) #Alternatively, use fig1
#We show only fig2
fig2.show() #Alternatively, use fig1
As of November 2020, in order to show one figure at a time, the following works:
import matplotlib.pyplot as plt
f1, ax1 = plt.subplots()
ax1.plot(range(0,10))
f1.show()
input("Close the figure and press a key to continue")
f2, ax2 = plt.subplots()
ax2.plot(range(10,20))
f2.show()
input("Close the figure and press a key to continue")
The call to input() prevents the figure from opening and closing immediately.

Categories