1

I am using python's plotnine package to create a series of plots. Often I need the plots to fit into a space x-cms by y-cms. I can control the size of the plot via:

p.save(filename=path+'fig1.png', height=10, width=12, units = 'cm', dpi=300)

But this sets the size of the plot area, whereas I need to set the size of the .png file (inclusive of titles, axis labels and legends.

That is, consider the following three plots. When inserted into a document, fig1, fig2, fig3 will take up a different amount of space in the document, necessitating some scaling. This scales other aspects of the plot such as font size.

import pandas as pd
from plotnine import *
from plotnine.data import mpg
    
path = 'C:\\Users\\BRB\\'
    
p = (ggplot(mpg, aes(x='displ', y='hwy', colour='factor(cyl)'))
  + geom_point()
)
p.save(filename=path+'fig1.png', height=10, width=12, units = 'cm', dpi=300)

p = (ggplot(mpg, aes(x='displ', y='hwy', colour='factor(cyl)'))
  + geom_point()
  + labs(x=None,y=None)
)
p.save(filename=path+'fig2.png', height=10, width=12, units = 'cm', dpi=300)

p = (ggplot(mpg, aes( x='displ', y='hwy', colour='factor(cyl)'))
  + geom_point()
  + labs(x=None,y=None)
  + scale_color_discrete(guide=False)
)
p.save(filename=path+'fig3.png', height=10, width=12, units = 'cm', dpi=300)

How can I fix the physical size of the whole png in plotnine? And are the dimensions in the save statement only approximate? When inserted into a Word document, the first figure is 9.22cms tall and the other 2 are 8.69cms (rather than 10) and the third figure is 10.47cms wide (rather than 12).

brb
  • 1,123
  • 17
  • 40

2 Answers2

1

I had a similar problem and I found a workaround converting the figure to matplotlib, then setting the size and then saving it:

p = (ggplot(mpg, aes(x='displ', y='hwy', colour='factor(cyl)'))
        + geom_point()
    )
fig = p.draw()
fig.set_size_inches(6.5, 3)
plt.savefig(path+'fig1.png')
  • Thanks, this is a helpful contribution but not quite perfect because while it saves the figures to be an exact size, it does so but cutting off various aspects. For example, the legend in figure 1 and figure 2 is partially cut off. It may be the case that the best options is to build a function that first saves the file, determines it's physical size, then adjusts the plotnine size calls to get the desired physical size. – brb Oct 06 '22 at 03:25
0

Regarding your second question, unfortunatly it is not possible to create an exact image with a exact size, as stated in this github issue.

Regarding your first question, what you could do is save the plot as a vector image (svg) and then (programatically) resize/move the img or the individual layers.

I hope this helps, it is unfortunatly one of the shortcomings of plotnine.

Cloudkollektiv
  • 11,852
  • 3
  • 44
  • 71