import io
import numpy as np
import pandas as pd
from lets_plot import *
LetsPlot.setup_html()
df = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/iris.csv")
print(df.shape)
df.head()
(150, 5)
sepal_length | sepal_width | petal_length | petal_width | species | |
---|---|---|---|---|---|
0 | 5.1 | 3.5 | 1.4 | 0.2 | setosa |
1 | 4.9 | 3.0 | 1.4 | 0.2 | setosa |
2 | 4.7 | 3.2 | 1.3 | 0.2 | setosa |
3 | 4.6 | 3.1 | 1.5 | 0.2 | setosa |
4 | 5.0 | 3.6 | 1.4 | 0.2 | setosa |
p = ggplot(df) + geom_point(aes("petal_length", "petal_width", color="species"), size=5) + ggsize(600, 400)
p
ggsave()
¶The ggsave()
function is an easy way to export plot to a file in SVG, PDF, HTML or PNG formats.
fullpath_svg = ggsave(p, "plot.svg")
Load and display saved SVG.
from IPython.display import SVG
SVG(filename=fullpath_svg)
fullpath_pdf = ggsave(p, "plot.pdf")
Load and display saved PDF.
from os import getcwd
from IPython.display import IFrame
IFrame(fullpath_pdf.replace(getcwd(), "."), width=600, height=400)
By default, when exporting HTML, ggsave
wraps the HTML of the plot in an iframe
that matches the size of the plot.
fullpath_html = ggsave(p, "plot.html")
Load and display saved HTML.
from IPython.display import HTML
HTML(filename=fullpath_html)
Use the iframe=False
option to only export the HTML of the plot, without adding an iframe
.
fullpath_no_iframe = ggsave(p, "no_iframe_plot.html", iframe=False)
HTML(filename=fullpath_no_iframe)
fullpath_png = ggsave(p, "plot.png")
Load and display saved PNG.
from IPython.display import Image
Image(filename=fullpath_png, width=600, height=400)
You can export figure created by ggplot()
or gggrid()
functions
to a vector or raster format using the following methods:
to_svg(path)
to_html(path, iframe)
to_png(path, scale)
to_pdf(path, scale)
To save plot to a file on disc, specify the file' pathname in path
.
To stream plot image to a file-like object, supply such object in the path
parameter instead of a pathname.
path = p.to_svg("lets-plot-images/to_svg_plot.svg")
SVG(path)
stream = io.BytesIO()
p.to_svg(stream)
SVG(stream.getvalue())
dpi
¶Parameters dpi
, w
, h
and unit
can be used to configure export to a raster image with required physical metrics. Aspect ratio must be maintained manually between ggsize()
and ggsave()
. Please note that using these parameters will disable the scale
parameter.
img_72 = ggsave(p, "72dpi_plot.png", w=8, h=4, unit='in', dpi=72)
Image(filename=img_72, width=800, height=600)
img_300 = ggsave(p, "300dpi_plot.png", w=8, h=4, unit='in', dpi=300)
Image(filename=img_300, width=800, height=600)