matplotlib does not show right and down sides of the graph [duplicate] - python

I am starting using the interactive plotting from Matplotlib:
%matplotlib notebook
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, figsize=(8, 3))
plt.plot([i for i in range (10)],np.random.randint(10, size=10))
plt.show()
Anyone knows if there is a way to hide the toolbars of the interactive mode?

I disabled the interactive mode buttons and toolbar with some python generated css.
Run the following in one of the notebook cells:
%%html
<style>
.output_wrapper button.btn.btn-default,
.output_wrapper .ui-dialog-titlebar {
display: none;
}
</style>
Unfortunately there's no good css selectors on the buttons, so I've tried to use as specific selector as possible, though this may end up disabling other buttons that you might generate in the output cell.
Indeed, this approach affects all output cells in the notebook.

Use the magic %matplotlib ipympl with canvas. toolbar_visible=False. To prevent double-appearence of figure, use plt. ioff() while instantiate figure:
import matplotlib.pyplot as plt
plt.ioff()
fig, ax = plt.subplots()
plt.ion()
fig.canvas.toolbar_visible = False
display(fig.canvas)
It's a little bit doubly, but so you know how to play with plt
Edit: Haven't mind you on jupyter. This works on jupyterlab

Related

Suppress display of final frame in matplotlib animation in jupyter

I am working on a project that involves generating a matplotlib animation using pyplot.imshow for the frames. I am doing this in a jupyter notebook. I have managed to get it working, but there is one annoying bug (or feature?) left. After the animation is created, Jupyter shows the last frame of the animation in the output cell. I would like the output to include the animation, captured as html, but not this final frame. Here is a simple example:
import numpy as np
from matplotlib import animation
from IPython.display import HTML
grid = np.zeros((10,10),dtype=int)
fig1 = plt.figure(figsize=(8,8))
ax1 = fig1.add_subplot(1,1,1)
def animate(i):
grid[i,i]=1
ax1.imshow(grid)
return
ani = animation.FuncAnimation(fig1, animate,frames=10);
html = HTML(ani.to_jshtml())
display(html)
I can use the capture magic, but that suppresses everything. This would be OK, but my final goal is to make this public, via binder, and make it as simple as possible for students to use.
I have seen matplotlib animations on the web that don't seem to have this problems, but those used plot, rather than imshow, which might be an issue.
Any suggestions would be greatly appreciated.
Thanks,
David
That's the answer I got from the same thing I was looking for in 'jupyter lab'. Just add plt.close().
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from IPython.display import HTML
grid = np.zeros((10,10),dtype=int)
fig1 = plt.figure(figsize=(8,8))
ax1 = fig1.add_subplot(1,1,1)
def animate(i):
grid[i,i]=1
ax1.imshow(grid)
return
ani = animation.FuncAnimation(fig1, animate,frames=10);
html = HTML(ani.to_jshtml())
display(html)
plt.close() # update

I'm confused about what the second parameter to matplotlib.axes does [duplicate]

I am using ipython-notebook a lot at the moment for numerical analysis and plotting of data. In the process of preparing publication quality plots there is a lot of tweaking to get the layout just right, however I can't get ipython/matplotlib to show me what I will be saving in the browser. Making the process more painful than it should be because I have to keep opening the new output file to check it.
Is there a way to get the image that is displayed inline to be the same as the image that is saved?
Example as follows, facecolor='gray' for clarity:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
fig = plt.figure(figsize=(6,4),facecolor='gray')
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
x = np.linspace(0,2*np.pi,1000)
y = np.sin(x)
ax.plot(x,y,label=r'$\sin(x)$')
ax.set_xlim(0,2*np.pi)
ax.set_ylim(-1.2,1.2)
ax.set_xlabel(r'$x$')
ax.set_ylabel(r'$y$')
ax.legend(loc='upper right', frameon=False)
fig.savefig('mypath.png',dpi=300, facecolor='gray')
plt.show()
Note here I have explicity chosen my axes dimensions so that they are equidistant from the two sides of the resulting image. This is respected in the saved image, but ignored in the image shown in the notebook:
Notebook displayed image:
Savefig image:
As noted by #andrew, the ipython magics are enforcing bbox_inches='tight' by default. This can be overridden using other magics as explained in the ipython documentation:
%matplotlib inline
%config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
produces an inline image identical to that produced by savefig.
The behavior is due to the fact that the magic %matplotlib inline defaults to using the
bbox_inches='tight' when rendering inline.
I know you asked about changing the behavior of plt.show(), but alternatively, you could change the behavior of savefig() to use the same settings as the notbeook.
fig.savefig('mypath.png',dpi=300, facecolor='gray', bbox_inches='tight')
New 'savefig' image:

How to remove a residual plot in Jupyter output after displaying a matplotlib animation?

I want to display an animation in Jupyter using Matplotlib. Here is some basic example:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
line, = ax.plot(np.random.rand(10))
ax.set_ylim(0, 1)
def update(data):
line.set_ydata(data)
return line,
def data_gen():
while True:
yield np.random.rand(10)
ani = animation.FuncAnimation(fig, update, data_gen, interval=100);
from IPython.display import HTML
HTML(ani.to_jshtml())
When I run the code for the first time (or after restarting the kernel) I get what I want:
However, when I run the very same code for the second time I get a leftover in the left bottom:
I noticed that when I add %matplotlib inline at the top, then I got the bad output even after restarting the kernel. Thus my guess is that I have to set the magic command %matplotlib to default at the top each time I create an animation, but I can't even find if %matplotlib have a default value.
I use Anaconda. Here are my versions:
Conda version: 4.4.10
Python version: Python 3.6.4 :: Anaconda, Inc.
IPython version: 6.2.1
Jupyter version: 5.4.0
I used plt.close() to stop the first (unwanted) plot, and have not seen issues running the animation in a separate cell. I believe the issue is similar to those linked in the comments, jupyter is automatically displaying an unwanted plot for the first two lines - fig, ax = plt.subplots()
line, = ax.plot(np.random.rand(10)). I tired suggestions such as using semicolons at end of lines and a few different magic attempts, but no joy. A more concrete solution will no doubt appear, but for now....

set IPython Notebook inline plots background not transparent

In IPython Notebook 3, when I use the Inline matplotlib backend, the png figures in the browser have a transparent background.
How do I set it to white instead?
Minimal example:
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([1,2])
Right click and save the image, the image has a transparent background, I would like it to be white instead.
Update
Tried to set figure.facecolor in matplotlibrc but it still displays a transparent png:
import matplotlib
print("facecolor before:")
print(matplotlib.rcParams["figure.facecolor"])
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([1,2])
print("facecolor after:")
print(matplotlib.rcParams["figure.facecolor"])
This code gives as output:
facecolor before:
1.0
facecolor after:
(1, 1, 1, 0)
Assuming the area that was transparent is everything surrounding the ax (subplot) you can try this:
%matplotlib inline
import matplotlib.pyplot as plt
fig, ax = plt.subplots(facecolor='w')
ax.plot([1,2])
If you want to have white background in figures permanently you need to modify you matplotlibrc file (located in your home folder under .matplotlib\) changing these parameters:
figure.facecolor = 1
But you can always save you figure automatically with any background you want (independent from what it was when the figure was created) by passing facecolor:
fig.savefig('filename.png', facecolor='w', transparent=False)
Another option, instead of setting facecolor, is to use the seaborn package.
Just run:
import seaborn as sns
it automatically sets the plot background and also gives better default colors for matplotlib.

Matplotlib figures not changing interactively - Canopy Ipython

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 ##

Categories