将curly大括号添加到ggplot2然后使用ggsave

Sam*_*aDS 11 r save curly-braces ggplot2

所以这与这个问题非常相关,这个答案是一个很好的解决方案.问题是当我尝试使用ggsave导出绘图时,花括号不存在.

例:

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)
Run Code Online (Sandbox Code Playgroud)

我没有打开使用RStudio导出按钮,因为它没有正确导出我的主题字体大小等.我还需要比76 dpi更高的分辨率.我需要一个解决方案来添加花括号到ggplot2图形,并能够使用ggsave保存它.

bap*_*ste 15

我不理解使用的逻辑,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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述