set IPython Notebook inline plots background not transparent - python

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.

Related

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

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

Show matplotlib figure statelessly

Here's how to create a "stateful" plot in matplotlib and show it in non-interactive mode:
import matplotlib.pyplot as plt
plt.plot([1,2,8])
plt.show()
I am more interested in the "stateless" approach as I wish to embed matplotlib in my own python library. The same plot can be constructed "statelessly" as follows:
from matplotlib.figure import Figure
fig = Figure()
ax = fig.subplots()
lines = ax.plot([1,2,8])
However I don't know how to show it without resorting to pyplot , which I don't want to do as I would like to build up my own display mechanism.
How do I show the figure without resorting to pyplot?

How do I change the default colormap for pyplot?

I would like to change the default colormap for pyplots from 'viridis' to 'Dark2'.
I tried:
changing the 'image.cmap' line in the matplotlibrc file
mpl.rcParams['image.cmap'] = 'Dark2'
mpl.pyplot.set_cmap('Dark2')
pyplot.set_cmap('Dark2')
Somehow none of these attempts worked. I also tried restarting the kernel afterwards and also restartet spyder itself but nothing changed. Now Im out of ideas.
import matplotlib as mpl
from matplotlib import pyplot
mpl.rcParams['image.cmap'] = 'Dark2'
mpl.pyplot.set_cmap('Dark2')
pyplot.set_cmap('Dark2')
I am always ending up with the default colors of the viridis colormap which starts with a blueish color and 2nd on orange one. I would like to see the green color from Dark2 first and than the orange one.
Appreciate your help !
cheers, Gerrit
I don't think plt.set_cmap works for your use case. Here are two options that should.
Use Seaborn's helper:
import seaborn as sns
sns.set_palette('Dark2')
Use Maplotlib rcParams:
from cycler import cycler
from matplotlib import pyplot as plt
plt.rcParams['axes.prop_cycle'] = cycler('color', plt.get_cmap('Dark2').colors)
You can use matplotlib.pyplot.set_cmap is the way to change the default colormap. If you run the code below, you should see the 'Dark2' colormap.
import matplotlib.pyplot as plt
import numpy as np
plt.set_cmap('Dark2')
plt.imshow(np.random.random((20, 20)))
plt.colorbar()
plt.show()

Cannot change default colormap in matplotlib

I am trying to set the default colormap (not just the color of a specific plot) for matplotlib in my jupyter notebook (Python 3). I found the commands: plt.set_cmap("gray") and mpl.rc('image', cmap='gray'), that should set the default colormap to gray, but both commands are just ignored during execution and I still get the old colormap.
I tried these two codes:
import matplotlib as mpl
mpl.rc('image', cmap='gray')
plt.hist([[1,2,3],[4,5,6]])
import matplotlib.pyplot as plt
plt.set_cmap("gray")
plt.hist([[1,2,3],[4,5,6]])
They should both generate a plot with gray tones. However, the histogram has colors, which correspond to the first two colors of the default colormap. What am I not getting?
Thanks to the comment of Chris, I found the issue, it's not the default colormap that I need to change but the default color cycle. it's described here: How to set the default color cycle for all subplots with matplotlib?
import matplotlib as mpl
import matplotlib.pyplot as plt
from cycler import cycler
# Set the default color cycle
colors=plt.cm.gray(np.linspace(0,1,3))
mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=colors)
plt.hist([[1,2,3],[4,5,6]])
Since you have two data sets your are passing, you'll need to specify two colors.
plt.hist([[1,2,3],[4,5,6]], color=['black','purple'])
You can make use of the color argument in matplotlib plot function.
import matplotlib.pyplot as plt
plt.hist([[1,2,3],[4,5,6]], color=['gray','gray'])
with this method you have to specify the color scheme for each dataset hence an array of colors as I have put it above.
If you are using a version of matplotlib between prio and 2.0 you need to use rcParams (still working in newer versions):
import matplotlib.pyplot as plt
plt.rcParams['image.cmap'] = 'gray'

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:

Categories