How do I increase the resolution of Matplotlib plots in Jupyter Book? - jupyterbook

I typically use plt.rcParams['figure.dpi'] = 300 to increase the resolution of Matplotlib plots in my Jupyter notebooks.
However, this setting does not seem to work with Jupyter Books.
Here are reproducible steps:
Create a Jupyter Book template with jupyter-book create mynewbook
To mynewbook/notebooks.ipynb, add a code cell with rcParams['figure.dpi'] = 600 just before the plot
Build this Jupyter Book with jupyter-book build --builder pdflatex mynewbook
The figure in notebooks.ipynb remains the default resolution (72 dpi?) instead of 600 dpi, even though the in-notebook resolution is 600 dpi. How can I increase the resolution of Matplotlib (and seaborn) plots in Jupyter Books?

In this post the author proposes to increase the resolution:
from matplotlib import pyplot
pyplot.rcParams['figure.dpi'] = 600
pyplot.rcParams['savefig.dpi'] = 600
This works for me.

Related

Why doesn't BokehJS show in a rendered Jupyter/IPython notebook on GitHub?

I have the following code in a Jupyter notebook:
import numpy as np
from bokeh.plotting import figure, show
from bokeh.io import output_notebook
N = 4000
x = np.random.random(size=N) * 100
x = np.random.random(size=N) * 100
radii = np.random.random(size=N) * 1.5
colors = ["#%02x%02x%02x" % (r, g, 150) for r, g in zip(np.floor(50+2*x), np.floor(30+2*y))]
output_notebook()
# Loading BokehJS ...
p = figure()
p.circle(x, y, radius=radii, fill_color=colors, fill_alpha=0.6, line_color=None)
show(p)
However, it does not show any plot or graphics; it simply is stuck on "Loading BokehJS".
In principle, this should work with nbviewer, as rendered notebooks are stripped of all Javascript on GitHub (I think?). In my experience however, it doesn't.
GitHub scrubs all JavaScript from all Jupyter notebooks before rendering them (presumably for security reasons). Bokeh requires JavaScript code from the client library BokehJS in order to render or do anything at all. Given this, I would not expect Bokeh plots in Jupyter notebooks to ever work on GitHub, unfortunately.
I would very much like for it to be workable, but it is entirely outside our control. I have reached out to GitHub asking for an option to disable rendering entirely for notebooks in a repo, on the reasoning that "not rendering at all" is preferable to "rendering but looking broken" but have not heard back from them.
Note that nbviewer does not strip JavaScript, which is why all the notebooks at the Bokeh nbviewer.org gallery show up just fine.

Matlab in Linux: fontsize different between eps and fig export

I wish to export figures both in eps and tiff (or png) using Matlab. Following this thread, I can change figure size and resolution conveniently. But now my problem is that the font sizes in my exported eps and tif files are very different.
For example:
1: using 300 dpi resolution to save a tif file:
r=300;
set(gcf, 'PaperUnits', 'inches', 'PaperPosition', [0 0 1024*2 1024*2]/r)
print(gcf,'-dtiff',sprintf('-r%d',r), 'contour.tif');
I get a very small font size (same applies when saving to png and jpg)
Perhaps the resolution is affecting the font size. Because when I set r=0 (i.e. resolution the same as the display), the font size is very close to what I want:
r=300;
set(gcf, 'PaperUnits', 'inches', 'PaperPosition', [0 0 1024*2 1024*2]/r)
print(gcf,'-dtiff',sprintf('-r%d',0), 'contour.tif');
But the problem is that such resolutions can not be published as zigzags. This can be seen when slightly zoomed in.
Just wondering how I can set all figure outputs to be consistent between formats, particularly between eps and tiffs, without using third party software (e.g. using Illustrator to export)?
I found this problem is associated with the missing font in linux. I use the following commands to resolve three machines installing different distros:
for a ubuntu machine, run:
sudo apt-get install xfonts-75dpi xfonts-100dpi
for a gentoo machine, run:
emerge -av media-fonts/font-adobe-100dpi media-fonts/font-adobe-75dpi liberation-fonts
for a centos machine, run:
yum install xorg-x11-fonts-75dpi xorg-x11-fonts-100dpi
I have to reboot the computer to make the configuration in effect.

iPython nbconvert and latex: use .eps instead of .png for plots

I have an iPython notebook that contains an inline plot (i.e. it contains the command plot(x,y)). When I issue the command ipython nbconvert --to latex --post PDF --SphinxTransformer.author='Myself' MyNotebook.ipynb the resulting .PDF file contains the figure, but it has been exported to .PNG, so it doesn't look very good (pixelated). How can I tell nbconvert to export all plots/figures to .EPS instead?
Thank you
First of all the notebook is not responsible for creating plots, but matplotlib and this allows to render your plots as eps, pdf, svg, etc. in great quality to be included in publications.
I agree that the default inline plot format, i.e. png is not optimal to be used for publications due to several reasons. As given in the github issue you posted in your answer, the inline backend can be configured to use svg instead of png by calling
%config InlineBackend.figure_format = 'svg'
in a code cell.
With this, the newly created plots will be vectorial, (as Matt said, already rendered pngs will not be converted!). These svgs are embedded in the notebook (svgs can be rendered by modern browsers) and are subsequently converted to pdfs by nbconvert. These pdfs fulfil the requirements of publication ready plots. However, be aware that the svgs can be really huge (compared with pngs) and may slow down the notebook handling significantly.
Your initial question was about eps graphics. As said above, matplotlib can render eps, hence, you can always do something like savefig('plot1.eps') to create the desired figures. That's actually the way I create my publication figures (png in notebook, eps in paper).
Let's assume we would get IPython to generate eps files (embedded but not renderable in the browser). The tex file generated by nbconvert is designed to work with pdflatex. If fed with eps files pdflatex would convert these to pdf to be included in the final document. So basically it does the same as nbconvert currently does with the svgs. Thus, there is no benefit.
Finally, I want to point out that, even though the tex files generated by nbconvert look great (especially the ones created using the master branch), IMHO there is no way to use these files without touching (e.g. adding captions, scaling images, ...). Therefore, you could always include the eps files at this step into your papers.
NBconvert does not run your code. So if you haven't plotted with SVG matplotlib backend it is not possible.
If you did so, then you need to write a nbconvert preprocessor that does svg-> eps and extend the relevant template to know how to embed EPS.
Evidently this is a missing feature in nbconvert. There is not currently a way to get publication quality plots in your final PDF: https://github.com/ipython/ipython/issues/3603
https://github.com/ipython/ipython/issues/3693

Saving MATLAB figures as PDF with quality 300 DPI, centered

I want to save a MATLAB figure as PDF, with quality 300 DPI, and centered.
So far I managed to save it, but the image appears cropped. I changed the page type to A3 and kind of solves the problem, but I am looking for something more elegant. I am doing it from the GUI, but maybe from the command line is easier in MATLAB.
Is there any package or script that makes this (fundamental task for publications and papers) a bit easier?
Try using the following command:
print -painters -dpdf -r300 test.pdf
You will, of course, already have to have a file named test.pdf in the current directory.
Some notes on the -commands as well.
-painters: this specifies the use of the painters alogrithm for the exporting.
-dpdf: specifies a vector image, specially a pdf in this case. This is through Ghostscript.
-r300: specifies a 300 dpi resolution. -r400 would be 400 dpi and so on.
On an off note. I tend to just save the figure as a high DPI tiff image and import that tiff into another program where I actually assemble my figure(s) for the paper. I tend to lean towards CorelDraw personally.
I would recommend to check the exportfig package
exportfig(gcf, path_to_file, 'format','pdf','Resolution', 300 )
also, you can check fig package, which is nice to call before the exportfig:
figure
plot(x,y)
fig
exportfig(gcf, path_to_file, 'format','pdf','Resolution', 300 )

How to export non-blurry eps images?

I'm exporting an image in Matlab using the eps format, but it smooths the image. Matlab does not blur the image using other formats such as png. I would like to know how to export a non-blurry image with eps format. Here is the resulting image using png:
And here is the resulting image using eps:
UPDATE:
The problem is reproducible on a Mac, and the issue is with the eps renderer rather than MATLAB. For e.g., saving imagesc(rand(20)) and viewing with Preview and GSview results in the following:
Preview screenshot
GSview screenshot
Clearly, the information is not lost. It is just not interpreted/read correctly by some EPS viewers. The solution is simple: use GSview to view your eps images. You can download it from here
On Macs especially, if your end application is latex/pdflatex, you will have to explicitly set it to use GS/GSview, because otherwise, it will default to the Quartz engine, which is baked into the OS.
PREVIOUS ANSWER:
I am unable to reproduce the behavior your described. Here is the code I used, tested using R2010b on WinXP 32-bit:
M = fspecial('gaussian',[20 20],5);
imagesc(M)
print('-dpng','a.png')
print('-depsc2','b.eps')
a.png
b.eps
Perhaps this is an issue with your EPS viewer...
not sure why it works but you can try doing the following:
eps2eps oldfile newfile
does the trick for me (on a mac os)
At first I thought you were doing something incorrectly, but then I remembered that this was an issue that was bothering the hell out of me a year or so ago. I couldn't come up with a way to "fix" this behaviour and from what I've researched, this is most likely a bug and several others have had this problem too and there is no known solution. Of course, I could be wrong about the last part and there might be solutions out there that have come out since I looked for them.
Any way, my workaround this problem was to use pcolor with shading flat instead of imagesc. When you export this to an eps format it preserves the image correctly. Example:
pcolor(rand(20));
shading flat
print('-depsc','figure.eps')
NOTE: You might see the appearance of thin, faint white lines along the anti-diagonals of each little square (depends on the OS & viewer). These are the edges of the graphics primitives that are used to render the image. However, this is not a flaw in MATLAB's export, but rather a fault in rendering in your EPS/PDF viewer. For e.g., with the default settings in Preview on my mac, these lines show up, whereas with the default in Adobe Reader 9.4, they don't appear.
If anyone is still interested in a workaround: Open the .eps-file with text editor and search for "interpolate". You'll probably find "/Interpolate true def" two or three times. Replace "true" with "false" and be happy :)
A note regarding Yoda's answer: in Preview in Mac OS X, you can make the thin white diagonal lines across each of the squares disappear by unchecking "Anti-alias text and screen art". Of course, the downside is that then any text (e.g. figure axes, etc) is not anti-aliased. Unfortunately, unchecking that has no effect on blurriness if you're using imagesc.
Another note is that if you use preview to make a pdf from your eps, the resulting pdf still displays correctly (non-blurry) when you open it in Acrobat.
I've been long struggling with this problem as well. So far, GSView is the only viewer I've found that displays the eps figures produced by Matlab (R2015b) correctly. eps2eps did not work for me (psutils 1.23).
The following eventually worked for me:
Export the figure to pdf, following the instructions here
pdf2ps file.pdf file.eps
I just wrote this simple drop-in replacement for imagesc. It doesn't support all but the most basic features, but I still hope it helps.
function h = imagesc4pdf(C)
[ny nx] = size(C);
px = bsxfun(#plus, [-0.5; 0.5; 0.5; -0.5], reshape(1:nx, [1 1 nx]));
py = bsxfun(#plus, [-0.5; -0.5; 0.5; 0.5], 1:ny);
n = numel(C);
px = reshape(repmat(px, [1 ny 1]), 4, n);
py = reshape(repmat(py, [1 1 nx]), 4, n);
h = patch(px, py, reshape(C,1,n), 'linestyle', 'none');
xlim([.5 nx+.5]);
ylim([.5 ny+.5]);
set(gca, 'ydir', 'reverse');
Apply opengl renderer to the figure
figure(gcf);
set(gcf,'renderer','opengl');
The blurring actually depends on the rendering software your viewer application or printer uses. To get good results all the time, make each pixel in your image an 8x8 block of pixels of the same color, i.e. resize the image like this:
im2 = imresize(im1, 8, 'nearest');
The blurring then only affects the pixels at the edge of each block. 8x8 blocks are best as they compress without nasty artifacts using DCT compression (sometimes used in eps files).
This page helped me a lot: http://tech.mof-mof.co.jp/blog/machine-learning-octave.html (written in Japanese, please use google translate for it)
And this is also helpful: Octave-Gnuplot-AquaTerm error: set terminal aqua enhanced title "Figure 1"...unknown terminal type"
I also answered at https://www.coursera.org/learn/machine-learning/discussions/weeks/2/threads/Dh-aRfqSEeaHSQ6l4xnh6g.
I reinstalled gnuplot like this:
$ brew cask install xquartz
$ brew cask install aquaterm
$ brew uninstall gnuplot
$ brew install gnuplot --with-aquaterm --with-x11 --with-qt # you can show other options by `$ brew options gnuplot`
You may edit ~/.octaverc like this:
setenv("GNUTERM", "qt")
and in octave window, after typing "system gnuplot", then
set pm3d interpolate 2, 2
After saving the file, open octave-cli.app, and type
imagesc(magic(3)), colorbar
I got this.