Change matplotlib figure rendering back to default in jupyter notebook - matplotlib

I ran %config InlineBackend.figure_format = 'retina' in a jupyter notebook to change the way the notebook renders matplotlib figures.
How do I reverse that without restarting the kernel?
I'm asking because some figures look better with %config InlineBackend.figure_format = 'retina' and some look better with the default settings. Just curious how can you switch between the two across the notebook.

This worked for me:
from matplotlib_inline.backend_inline import set_matplotlib_formats
set_matplotlib_formats('svg')
I found you can set the format to:
'png'
'retina'
'jpeg'
'svg'
'pdf
Where each has some pros and cons.

Related

Matplotlib fonts not found in Google Colab [duplicate]

Using custom fonts in matplotlib locally involves storing the .ttfs in the matplotlib/mpl-data/fonts/ttf/ folder, then calling mpl.font_manager._rebuild(), then setting mpl.rcParams['font.sans-serif'].
Is there any way to do this in Google Colaboratory, where it doesn't seem that this ttf folder is accessible?
For example, I'd like to use the Roboto font. After installing, this would be invoked using mpl.rcParams['font.sans-serif'] = 'Roboto'.
The ttf folder is here:
/usr/local/lib/python3.6/dist-packages/matplotlib/mpl-data/fonts/ttf
So you want to download the ttf there, e.g.:
!wget https://github.com/Phonbopit/sarabun-webfont/raw/master/fonts/thsarabunnew-webfont.ttf -P /usr/local/lib/python3.6/dist-packages/matplotlib/mpl-data/fonts/ttf
matplotlib.font_manager._rebuild()
matplotlib.rc('font', family='TH Sarabun New')
update 2019-12
_rebuild() no longer works. Here's another method which still works.
import matplotlib
import matplotlib.font_manager as fm
!wget https://github.com/Phonbopit/sarabun-webfont/raw/master/fonts/thsarabunnew-webfont.ttf
fm.fontManager.ttflist += fm.createFontList(['thsarabunnew-webfont.ttf'])
matplotlib.rc('font', family='TH Sarabun New')
Wanted to add a full, succinct answer that currently works.
# Download fonts of choice. Here we download Open Sans variants to
# the current directory.
# It's not necessary to download to the share or matplotlib folders:
# /usr/share/fonts/truetype
# /usr/local/lib/python3.6/dist-packages/matplotlib/mpl-data/fonts/ttf
!wget 'https://github.com/google/fonts/raw/master/apache/opensans/OpenSans-Regular.ttf'
!wget 'https://github.com/google/fonts/raw/master/apache/opensans/OpenSans-Light.ttf'
!wget 'https://github.com/google/fonts/raw/master/apache/opensans/OpenSans-SemiBold.ttf'
!wget 'https://github.com/google/fonts/raw/master/apache/opensans/OpenSans-Bold.ttf'
from matplotlib import font_manager as fm, pyplot as plt
# Pick up any fonts in the current directory.
# If you do end up downloading the fonts to /usr/share/fonts/truetype,
# change this to: fm.findSystemFonts()
font_files = fm.findSystemFonts('.')
# Go through and add each to Matplotlib's font cache.
for font_file in font_files:
fm.fontManager.addfont(font_file)
# Use your new font on all your plots.
plt.rc('font', family='Open Sans')
Note, a few times this didn't work properly and the requested font wasn't displayed (even though no error or warning was shown). If that happens, try factory resetting your Colab runtime and running again.
When matplotlib 3.2 is released, it will be easier.
# For now we must upgrade to 3.2 rc first
# !pip install -U --pre matplotlib
import matplotlib as mpl
mpl.font_manager.fontManager.addfont('thsarabunnew-webfont.ttf')
mpl.rc('font', family='TH Sarabun New')
I would like to add my solutions as another reference:
Change the seaborn style
I would strongly recommend this approach as changing the font family can be very troublesome and inconvenient per seaborn design (many of the posts are no longer working on my end in 2022/05). So if you just want to get rid of the stupid default font in matplotlib and seaborn and is OK with Arial, go and type
%matplotlib inline
import matplotlib.style as style
style.use('seaborn-deep')
Changing the font type (borrowed from top answers and tested myself. Restarting the runtime several times if it is not working as expected)
import matplotlib as mpl
import matplotlib.font_manager as fm
from matplotlib import font_manager as fm, pyplot as plt
!wget https://github.com/trishume/OpenTuringCompiler/blob/master/stdlib-sfml/fonts/Times%20New%20Roman.ttf
!wget https://github.com/matomo-org/travis-scripts/blob/master/fonts/Arial.ttf
font_files = fm.findSystemFonts()
# Go through and add each to Matplotlib's font cache.
for font_file in font_files:
fm.fontManager.addfont(font_file)
fm.fontManager.ttflist += fm.createFontList(['Times New Roman.ttf'])
# Use your new font on all your plots.
plt.rc('font', family='serif')
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2*np.pi*t)
plt.plot(t, s)
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('About as simple as it gets, folks')
plt.show()
Updates on 2022/06/08: Method 1 sometimes doesn't work out in Colab, but it works on the local Jupyter Notebook. It seems that explicitly installing and adding the font types is the only way if you want to customize font types on Colab.

JupyterLab fig does not show. It shows blank result (but works fine on jupyternotebook)

I am new to JupyterLab trying to learn.
When I try to plot a graph, it works fine on jupyter notebook, but does not show the result on jupyterlab. Can anyone help me with this?
Here are the codes below:
import pandas as pd
import pandas_datareader.data as web
import time
# import matplotlib.pyplot as plt
import datetime as dt
import plotly.graph_objects as go
import numpy as np
from matplotlib import style
# from matplotlib.widgets import EllipseSelector
from alpha_vantage.timeseries import TimeSeries
Here is the code for plotting below:
def candlestick(df):
fig = go.Figure(data = [go.Candlestick(x = df["Date"], open = df["Open"], high = df["High"], low = df["Low"], close = df["Close"])])
fig.show()
JupyterLab Result:
Link to the image (JupyterLab)
JupyterNotebook Result:
Link to the image (Jupyter Notebook)
I have updated both JupyterLab and Notebook to the latest version. I do not know what is causing JupyterLab to stop showing the figure.
Thank you for reading my post. Help would be greatly appreciated.
Note*
I did not include the parts for data reading (Stock OHLC values). It contains the API keys. I am sorry for inconvenience.
Also, this is my second post on stack overflow. If this is not a well-written post, I am sorry. I will try to put more effort if it is possible. Thank you again for help.
TL;DR:
run the following and then restart your jupyter lab
jupyter labextension install #jupyterlab/plotly-extension
Start the lab with:
jupyter lab
Test with the following code:
import plotly.graph_objects as go
from alpha_vantage.timeseries import TimeSeries
def candlestick(df):
fig = go.Figure(data = [go.Candlestick(x = df.index, open = df["1. open"], high = df["2. high"], low = df["3. low"], close = df["4. close"])])
fig.show()
# preferable to save your key as an environment variable....
key = # key here
ts = TimeSeries(key = key, output_format = "pandas")
data_av_hist, meta_data_av_hist = ts.get_daily('AAPL')
candlestick(data_av_hist)
Note: Depending on system and installation of JupyterLab versus bare Jupyter, jlab may work instead of jupyter
Longer explanation:
Since this issue is with plotly and not matplotlib, you do NOT have to use the "inline magic" of:
%matplotlib inline
Each extension has to be installed to the jupyter lab, you can see the list with:
jupyter labextension list
For a more verbose explanation on another extension, please see related issue:
jupyterlab interactive plot
Patrick Collins already gave the correct answer.
However, the current JupyterLab might not be supported by the extension, and for various reasons one might not be able to update the JupyterLab:
ValueError: The extension "#jupyterlab/plotly-extension" does not yet support the current version of JupyterLab.
In this condition a quick workaround would be to save the image and show it again:
from IPython.display import Image
fig.write_image("image.png")
Image(filename='image.png')
To get the write_image() method of Plotly to work, kaleido must be installed:
pip install -U kaleido
This is a full example (originally from Plotly) to test this workaround:
import os
import pandas as pd
import plotly.express as px
from IPython.display import Image
df = pd.DataFrame([
dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Resource="Alex"),
dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15', Resource="Alex"),
dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30', Resource="Max")
])
fig = px.timeline(df, x_start="Start", x_end="Finish", y="Resource", color="Resource")
if not os.path.exists("images"):
os.mkdir("images")
fig.write_image("images/fig1.png")
Image(filename='images/fig1.png')

Custom fonts in Google Colaboratory matplotlib charts

Using custom fonts in matplotlib locally involves storing the .ttfs in the matplotlib/mpl-data/fonts/ttf/ folder, then calling mpl.font_manager._rebuild(), then setting mpl.rcParams['font.sans-serif'].
Is there any way to do this in Google Colaboratory, where it doesn't seem that this ttf folder is accessible?
For example, I'd like to use the Roboto font. After installing, this would be invoked using mpl.rcParams['font.sans-serif'] = 'Roboto'.
The ttf folder is here:
/usr/local/lib/python3.6/dist-packages/matplotlib/mpl-data/fonts/ttf
So you want to download the ttf there, e.g.:
!wget https://github.com/Phonbopit/sarabun-webfont/raw/master/fonts/thsarabunnew-webfont.ttf -P /usr/local/lib/python3.6/dist-packages/matplotlib/mpl-data/fonts/ttf
matplotlib.font_manager._rebuild()
matplotlib.rc('font', family='TH Sarabun New')
update 2019-12
_rebuild() no longer works. Here's another method which still works.
import matplotlib
import matplotlib.font_manager as fm
!wget https://github.com/Phonbopit/sarabun-webfont/raw/master/fonts/thsarabunnew-webfont.ttf
fm.fontManager.ttflist += fm.createFontList(['thsarabunnew-webfont.ttf'])
matplotlib.rc('font', family='TH Sarabun New')
Wanted to add a full, succinct answer that currently works.
# Download fonts of choice. Here we download Open Sans variants to
# the current directory.
# It's not necessary to download to the share or matplotlib folders:
# /usr/share/fonts/truetype
# /usr/local/lib/python3.6/dist-packages/matplotlib/mpl-data/fonts/ttf
!wget 'https://github.com/google/fonts/raw/master/apache/opensans/OpenSans-Regular.ttf'
!wget 'https://github.com/google/fonts/raw/master/apache/opensans/OpenSans-Light.ttf'
!wget 'https://github.com/google/fonts/raw/master/apache/opensans/OpenSans-SemiBold.ttf'
!wget 'https://github.com/google/fonts/raw/master/apache/opensans/OpenSans-Bold.ttf'
from matplotlib import font_manager as fm, pyplot as plt
# Pick up any fonts in the current directory.
# If you do end up downloading the fonts to /usr/share/fonts/truetype,
# change this to: fm.findSystemFonts()
font_files = fm.findSystemFonts('.')
# Go through and add each to Matplotlib's font cache.
for font_file in font_files:
fm.fontManager.addfont(font_file)
# Use your new font on all your plots.
plt.rc('font', family='Open Sans')
Note, a few times this didn't work properly and the requested font wasn't displayed (even though no error or warning was shown). If that happens, try factory resetting your Colab runtime and running again.
When matplotlib 3.2 is released, it will be easier.
# For now we must upgrade to 3.2 rc first
# !pip install -U --pre matplotlib
import matplotlib as mpl
mpl.font_manager.fontManager.addfont('thsarabunnew-webfont.ttf')
mpl.rc('font', family='TH Sarabun New')
I would like to add my solutions as another reference:
Change the seaborn style
I would strongly recommend this approach as changing the font family can be very troublesome and inconvenient per seaborn design (many of the posts are no longer working on my end in 2022/05). So if you just want to get rid of the stupid default font in matplotlib and seaborn and is OK with Arial, go and type
%matplotlib inline
import matplotlib.style as style
style.use('seaborn-deep')
Changing the font type (borrowed from top answers and tested myself. Restarting the runtime several times if it is not working as expected)
import matplotlib as mpl
import matplotlib.font_manager as fm
from matplotlib import font_manager as fm, pyplot as plt
!wget https://github.com/trishume/OpenTuringCompiler/blob/master/stdlib-sfml/fonts/Times%20New%20Roman.ttf
!wget https://github.com/matomo-org/travis-scripts/blob/master/fonts/Arial.ttf
font_files = fm.findSystemFonts()
# Go through and add each to Matplotlib's font cache.
for font_file in font_files:
fm.fontManager.addfont(font_file)
fm.fontManager.ttflist += fm.createFontList(['Times New Roman.ttf'])
# Use your new font on all your plots.
plt.rc('font', family='serif')
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2*np.pi*t)
plt.plot(t, s)
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('About as simple as it gets, folks')
plt.show()
Updates on 2022/06/08: Method 1 sometimes doesn't work out in Colab, but it works on the local Jupyter Notebook. It seems that explicitly installing and adding the font types is the only way if you want to customize font types on Colab.

matplotlib configuration for inline backend in jupyter notebook

I'd like to learn how to configure the defaults for matplotlib using the inline backend in jupyter notebook. Specifically, I'd like to set default 'figure.figsize’ to [7.5, 5.0] instead of the default [6.0, 4.0]. I’m using jupyter notebook 1.1 on a Mac with matplotlib 1.4.3.
In the notebook, using the macosx backend, my matplotlibrc file is shown to be in the standard location, and figsize is set as specified in matplotlibrc:
In [1]: %matplotlib
Using matplotlib backend: MacOSX
In [2]: mpl.matplotlib_fname()
Out[2]: u'/Users/scott/.matplotlib/matplotlibrc'
In [3]: matplotlib.rcParams['figure.figsize']
Out[3]:[7.5, 5.0]
However, when I use the inline backend, figsize is set differently:
In [1]: %matplotlib inline
In [2]: mpl.matplotlib_fname()
Out[2]: u'/Users/scott/.matplotlib/matplotlibrc'
In [3]: matplotlib.rcParams['figure.figsize']
Out[3]:[6.0, 4.0]
In my notebook config file, ~/.jupyter/jupyter_notebook_config.py, I also added the line
c.InlineBackend.rc = {'figure.figsize': (7.5, 5.0) }
but this had no effect either. For now I’m stuck adding this line in every notebook:
matplotlib.rcParams['figure.figsize']=[7.5, 5.0]
Is there any way to set the default for the inline backend?
The Jupyter/IPython split is confusing. Jupyter is the front end to kernels, of which IPython is the defacto Python kernel. You are trying to change something related to matplotlib and this only makes sense within the scope of the IPython kernel. Making a change to matplotlib in ~/.jupyter/jupyter_notebook_config.py would apply to all kernels which may not make sense (in the case of running a Ruby/R/Bash/etc. kernel which doesn't use matplotlib). Therefore, your c.InlineBackend.rc setting needs to go in the settings for the IPython kernel.
Edit the file ~/.ipython/profile_default/ipython_kernel_config.py and add to the bottom: c.InlineBackend.rc = { }.
Since c.InlineBackend.rc specifies matplotlib config overrides, the blank dict tells the IPython kernel not to override any of your .matplotlibrc settings.
If the file doesn't exist, run ipython profile create to create it.
Using Jupyter on windows at least, I was able to do it using something very much like venkat's answer, i.e.:
%matplotlib inline
import matplotlib
matplotlib.rcParams['figure.figsize'] = (8, 8)
I did this to square the circle, which had been rather eliptical up to that point. See, squaring the circle is not that hard. :)
Note that the path of ipython_kernel_config.py differs if you run ipython from a virtual environment. In that case, dig in the path where the environment is stored.
Use figsize(width,height) in the top cell and it changes width of following plots
For jupyter 5.x and above with IPython kernels, you can just override particular keys and leave the rest by putting things like this, with your desired figsize in your ~/.ipython/profile_default/ipython_kernel_config.py:
c = get_config()
c.InlineBackend.rc.update({"figure.figsize": (12, 10)})

Jupyter notebook matplotlib figures missing in exported pdf

When generating a pdf in jupyter notebook, everything works great, but I would like to keep the inline figures inside the pdf, as well as the notebook.
Here is my code:
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('png', 'pdf')
save_figures = True
x = np.arange(0, 20, 0.1)
y = np.sin(x)
plt.figure()
plt.plot(x, y)
if save_figures:
plt.savefig('test.png')
plt.show()
The figures appear inline, but in the pdf what is printed instead is:
<IPython.core.display.Javascript object>
<IPython.core.display.HTML object>
The same thing appears in the pdf if I export from the web or use nbconvert to export to pdf from the command line.
Are there any additional commands that I need to invoke in order to get this to work?
If you change the %matplotlib notebook to %matplotlib inline, then PDF export with jupyter's nbconvert works fine for me. The %matplotlib notebook magic renders the plot in an interactive way that I suspect isn't properly recognized by LaTeX, which is used during the PDF conversion.
Alternatively, if you have to use %matplotlib notebook for some reason, the export to HTML with jupyter's nbconvert (jupyter nbconvert --to='html' Test.ipynb) seems to preserve the plot. I am then able to print this HTML file to a PDF from a web browser and the plot is present in the final PDF.
Crude solution to interactive problem:
in interactive function save figure to a file
fig.savefig("pieCharts.png")
in next cell display a file:
from IPython.display import Image
Image("pieCharts.png")
In PDF only output of the 2nd line will be displayed with image as changed in interactive function.