简体   繁体   中英

Increase DPI of Matplotlib .show() in Jupyter Notebook

I'm using Matplotlib in a Jupyter Notebook to display an image of a map. The code looks like this:

%matplotlib inline

imgpath = './map.png'

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np

from PIL import Image

img = Image.open(imgpath)
print(img.size)

width, height = img.size
# img.thumbnail((width * 2,height * 2), Image.ANTIALIAS)  # resizes image in-place
imgplot = plt.imshow(img)
plt.savefig('test.png', dpi = 300)

The problem is, although the plt.savefig('test.png', dpi = 300) looks fine (because I changed the dpi to 300), the image displayed in the notebook is so low resolution I can't make anything out on it, and plt.imshow(img, dpi = 300) doesn't work:

笔记本中显示的图像

So what I'm wondering is if there is a way to change the resolution of the image shown in the Jupyter Notebook?

Add this at the beginning of the notebook:

import matplotlib as mpl
mpl.rcParams['figure.dpi'] = 300

That's it !

If your screen has Retina display, add the following line after %matplotlib inline (or somewhere else before plotting) in your notebook

%config InlineBackend.figure_format = 'retina'

This will increase the display resolution of your plots within the Jupyter Notebook.

Using the solution proposed in this answer has the drawbacks to apply the DPI to all the other figures that will be created within the notebook.

This is fine in most cases, but if you need to set the DPI value ONLY for one figure, you can do it as follows:

plt.imshow(img)
plt.gcf().set_dpi(300)
plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM