gpt4 book ai didi

r - 以给定的纵横比保存绘图

转载 作者:行者123 更新时间:2023-12-05 07:55:01 26 4
gpt4 key购买 nike

我正在使用非常棒的库 ggplot2。我想出了如何使用 coord_fixed 设置绘图的纵横比。现在,我想将绘图保存为具有指定宽度(例如 10 厘米)的 PDF,并计算所需的高度。我不知道如何实现这一目标。这可能吗?

最佳答案

您可以使用网格函数来计算 ggplot grob 的完整大小,但有(编辑: 至少)两个注意事项:

  • 将打开一个额外的设备窗口,进行单位转换

  • 绘图面板大小默认为 0,因为它是根据它所在的设备(视口(viewport))即时计算的,而不是相反。

也就是说,以下函数尝试打开一个完全适合 ggplot 的设备,

library(ggplot2)
library(grid)

sizeit <- function(p, panel.size = 2, default.ar=1){

gb <- ggplot_build(p)
# first check if theme sets an aspect ratio
ar <- gb$plot$coordinates$ratio

# second possibility: aspect ratio is set by the coordinates, which results in
# the use of 'null' units for the gtable layout. let's find out
g <- ggplot_gtable(gb)
nullw <- sapply(g$widths, attr, "unit")
nullh <- sapply(g$heights, attr, "unit")

# ugly hack to extract the aspect ratio from these weird units
if(any(nullw == "null"))
ar <- unlist(g$widths[nullw == "null"]) / unlist(g$heights[nullh == "null"])

if(is.null(ar)) # if the aspect ratio wasn't specified by the plot
ar <- default.ar

# ensure that panel.size is always the larger dimension
if(ar <= 1 ) panel.size <- panel.size / ar

g$fullwidth <- convertWidth(sum(g$widths), "in", valueOnly=TRUE) +
panel.size
g$fullheight <- convertHeight(sum(g$heights), "in", valueOnly=TRUE) +
panel.size / ar

class(g) <- c("sizedgrob", class(g))
g
}


print.sizedgrob <- function(x){
# note: dev.new doesn't seem to respect those parameters
# when called from Rstudio; in this case it
# may be replaced by x11 or quartz or ...
dev.new(width=x$fullwidth, height=x$fullheight)
grid.draw(x)
}


p1 <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + coord_fixed() +
theme(plot.background = element_rect(colour = "red"))

p2 <- p1 + aes(x = mpg, y = wt)

# need for an explicit dummy device open, otherwise it's a bit off
# for no apparent reason that I can understand
dev.new()

sizeit(p1, 0.1)

enter image description here

sizeit(p2, 2)

enter image description here

关于r - 以给定的纵横比保存绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30458813/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com