CoCalc Logo Icon
StoreFeaturesDocsShareSupport News Sign UpSign In
Views: 32
Image: ubuntu2204-dev
Embed | Download | Raw |
Kernel: Python 3 (system-wide)

SVG or PNG plots in CoCalc Notebooks

SVGhigher resolutionsize and rendering time proportional to number of elements
PNGscreen resolution, could be 2x oversampled for high res monitorsconstant size, proportional to number of pixels and overall complexity, constant rendering time

NOTE: This is for the Python 3 kernel. It does not work for the SageMath kernels. See 35972.

import matplotlib.pyplot as plt import numpy as np xx = np.linspace(-3, 10, 1000) yy = np.sin(xx**2)

Default: PNG plots with 2x oversampling ("retina")

This is configured by default on CoCalc via

%config InlineBackend.figure_formats = 'retina'

This plot has a size of about 142kB and works well on modern high resolution screens.

plt.plot(xx, yy)
[<matplotlib.lines.Line2D at 0x7f20febf2bf0>]
Image in a Jupyter notebook

... or as just a simpler PNG without oversampling, with a size of just about 60kB. If you have a high resolution screen, you'll notice fuzziness around sharp edges and characters.

%config InlineBackend.figure_formats = 'png'
plt.plot(xx, yy)
[<matplotlib.lines.Line2D at 0x7f20fe950d60>]
Image in a Jupyter notebook


Configure the backend for drawing inline plots to use SVG

The plot below has a size of only 27kB.

%config InlineBackend.figure_formats = 'svg'
plt.plot(xx, yy)
[<matplotlib.lines.Line2D at 0x7f20fea84820>]
Image in a Jupyter notebook

10.000 points?

Here, SVG grows larger than PNG.

Warning If you up this to 100.000 and plot SVG, your browser might eat up a lot of your computers resources, since it has to draw so much!

uu = np.random.randn(10_000) vv = np.random.randn(10_000)
%config InlineBackend.figure_formats = 'png'

This PNG plot has about 110kB.

plt.plot(uu, vv, color='black', marker='.', linestyle="none", alpha=0.1)
[<matplotlib.lines.Line2D at 0x7f20feb1e650>]
Image in a Jupyter notebook
%config InlineBackend.figure_formats = 'svg'

While this SVG is more than 1MB (compressed it is less, though), and it takes a bit to even render it in your browser. With more elements to draw, the local performance of showing this SVG will suffer even more, while the performance of rendering a PNG is essentially constant.

plt.plot(uu, vv, color='black', marker='.', linestyle="none", alpha=0.1)
[<matplotlib.lines.Line2D at 0x7f20fc808b80>]