Saving a plotnine graph to png¶
Once you're done with exploratory data analysis, it's time to show your graphic to the world! That's when you export.
import pandas as pd
from plotnine import *
df = pd.DataFrame([
{ 'amount': 34, 'category': 'almonds'},
{ 'amount': 11, 'category': 'strawberries'},
{ 'amount': 20, 'category': 'oats'},
])
df
amount | category | |
---|---|---|
0 | 34 | almonds |
1 | 11 | strawberries |
2 | 20 | oats |
Saving as a png¶
Unless you're going to be editing it in software like Adobe Illustrator, you usually want to save your graphic as a png! If you went with a jpeg file you're going to lose quality!
To save your graph, just save the graph as a variable and use .save('filename.png')
.
chart = (
ggplot(df)
+ aes(x='category', y='amount')
+ geom_bar(stat='identity')
)
chart.save("filename.png")
chart
/Users/soma/Development/plotnine/plotnine/ggplot.py:731: PlotnineWarning: Saving 6.4 x 4.8 in image. /Users/soma/Development/plotnine/plotnine/ggplot.py:734: PlotnineWarning: Filename: filename.png
<ggplot: (311459307)>
Changing the size of the output file¶
Sometimes you want a bigger or smaller image! To do this, you'll need to adjust the figure_size
with the theme
. It's in inches, which is very weird, but that's life. Just make it until the size seems right.
chart = (
ggplot(df)
+ aes(x='category', y='amount')
+ geom_bar(stat='identity')
+ theme(figure_size=(10, 3))
)
chart.save("filename.png")
chart
/Users/soma/Development/plotnine/plotnine/ggplot.py:731: PlotnineWarning: Saving 10 x 3 in image. /Users/soma/Development/plotnine/plotnine/ggplot.py:734: PlotnineWarning: Filename: filename.png
<ggplot: (313950067)>
In theory you can also change the resolution by passing dpi=
but... it doesn't really matter (I think) unless you're doing something for print publications or getting fancy with multiple resolution images for retina screens.