在ggplot2中添加大括号,然后使用ggsave

2023-12-19

所以这与此非常相关question https://stackoverflow.com/questions/7001799/ggplot2-curly-braces-on-an-axis和这个answer https://stackoverflow.com/a/33544572/1582926是一个很好的解决方案。

问题是,当我尝试使用 ggsave 导出绘图时,大括号不存在。

example:

library(ggplot2)
library(grid)
library(pBrackets) 

x <- c(runif(10),runif(10)+2)
y <- c(runif(10),runif(10)+2)

the_plot <- qplot(x=x,y=y) +
  scale_x_continuous("",breaks=c(.5,2.5),labels=c("Low types","High types") ) +
  theme(axis.ticks = element_blank(),
        axis.ticks.length = unit(.85, "cm"))
the_plot

grid.locator(unit="native") 
bottom_y <- 284 

grid.brackets(220, bottom_y,   80, bottom_y, lwd=2, col="red")
grid.brackets(600, bottom_y,  440, bottom_y, lwd=2, col="red")

ggsave("test.png",width = 4, height = 2.5)

我不愿意使用 RStudio 导出按钮,因为它无法正确导出我的主题字体大小等。我还需要高于 76 dpi 的分辨率。我需要一个解决方案来向 ggplot2 图形添加大括号并能够使用 ggsave 保存它。


Answer recommended by R Language /collectives/r-language Collective

我不明白其中使用的逻辑grid.brackets但如果有的话会有帮助bracketsGrob函数会简单地返回一个 grob 而不绘制它。也许联系维护人员提出功能请求?

无论如何,假设这样的功能可用,它可以被提供给annotation_custom使其兼容ggsave.

bracketsGrob <- function(...){
l <- list(...)
e <- new.env()
e$l <- l
  grid:::recordGrob(  {
    do.call(grid.brackets, l)
  }, e)
}

# note that units here are "npc", the only unit (besides physical units) that makes sense
# when annotating the plot panel in ggplot2 (since we have no access to 
# native units)

b1 <- bracketsGrob(0.33, 0.05, 0, 0.05, h=0.05, lwd=2, col="red")
b2 <- bracketsGrob(1, 0.05, 0.66, 0.05, h=0.05,  lwd=2, col="red")

p <- the_plot + 
  annotation_custom(b1)+ 
  annotation_custom(b2) +
  scale_y_continuous(expand=c(0.11,0))
p

ggsave("test.png", p, width = 4, height = 2.5)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在ggplot2中添加大括号,然后使用ggsave 的相关文章

随机推荐