@@ -99,8 +99,12 @@ ggsave <- function(filename, plot = get_last_plot(),
99
99
100
100
dpi <- parse_dpi(dpi )
101
101
dev <- validate_device(device , filename , dpi = dpi )
102
- dim <- plot_dim(c(width , height ), scale = scale , units = units ,
103
- limitsize = limitsize , dpi = dpi )
102
+ dim <- plot_dim(
103
+ width = width , height = height ,
104
+ scale = scale , units = units ,
105
+ limitsize = limitsize , dpi = dpi ,
106
+ plot = plot
107
+ )
104
108
105
109
if (is_null(bg )) {
106
110
bg <- calc_element(" plot.background" , plot_theme(plot ))$ fill %|| % " transparent"
@@ -189,12 +193,44 @@ parse_dpi <- function(dpi, call = caller_env()) {
189
193
}
190
194
}
191
195
192
- plot_dim <- function (dim = c( NA , NA ) , scale = 1 , units = " in" ,
193
- limitsize = TRUE , dpi = 300 , call = caller_env()) {
196
+ plot_dim <- function (width = NA , height = NA , scale = 1 , units = " in" ,
197
+ limitsize = TRUE , dpi = 300 , plot = NULL , call = caller_env()) {
194
198
units <- arg_match0(units , c(" in" , " cm" , " mm" , " px" ))
195
- to_inches <- function (x ) x / c(`in` = 1 , cm = 2.54 , mm = 2.54 * 10 , px = dpi )[units ]
199
+ to_inches <- function (x ) x / c(`in` = 1 , cm = 2.54 , mm = 2.54 * 10 , px = dpi )[units ]
196
200
from_inches <- function (x ) x * c(`in` = 1 , cm = 2.54 , mm = 2.54 * 10 , px = dpi )[units ]
197
201
202
+ if (is.derived(width ) || is.derived(height )) {
203
+ if (is.ggplot(plot )) {
204
+ plot <- ggplotGrob(plot )
205
+ }
206
+ if (! inherits(plot , " gtable" )) {
207
+ cli :: cli_abort(
208
+ " Cannot derive size of plot when {.arg plot} is \\
209
+ {.obj_type_friendly {plot}}." ,
210
+ call = call
211
+ )
212
+ }
213
+ width <- if (is.derived(width )) gtable_width(plot ) else width
214
+ height <- if (is.derived(height )) gtable_height(plot ) else height
215
+ }
216
+
217
+ if (is.unit(width )) {
218
+ if (has_null_unit(width )) {
219
+ width <- NA
220
+ } else {
221
+ width <- from_inches(convertWidth(width , " in" , valueOnly = TRUE ))
222
+ }
223
+ }
224
+
225
+ if (is.unit(height )) {
226
+ if (has_null_unit(height )) {
227
+ height <- NA
228
+ } else {
229
+ height <- from_inches(convertHeight(height , " in" , valueOnly = TRUE ))
230
+ }
231
+ }
232
+
233
+ dim <- c(width , height )
198
234
dim <- to_inches(dim ) * scale
199
235
200
236
if (anyNA(dim )) {
0 commit comments