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

R 将大括号添加到ggplot2,然后使用ggsave,r,ggplot2,save,curly-braces,R,Ggplot2,Save,Curly Braces,这与此非常相关,这是一个很好的解决方案 问题是,当我尝试使用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),label

这与此非常相关,这是一个很好的解决方案

问题是,当我尝试使用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)
库(ggplot2)
图书馆(网格)
图书馆(公共图书馆)

x我想你可以用设备做点什么,作为
ggsave
的替代品,我终于让它起作用了。由于R-Studio不知何故对哪些设备实际处于打开或关闭(关闭)状态感到困惑,所以这比它本应付出的努力要多。因此,有时您必须重置R会话。检查
dev.list()
会有很大帮助。有点

但是经过一点测试,这个序列工作得相当可靠

我也使用jpeg进行了测试,因为我可以在windows中使用文件属性命令查看分辨率,以查看我指定的分辨率(200 ppi)是否通过:

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

# User has to click here to specify where the brackets go
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")

#dev.copy(png,"mypng.png",height=1000,width=1000,res=200)
dev.copy(jpeg,"myjpg.jpg",height=1000,width=1000,res=200) 
dev.off()
库(ggplot2)
图书馆(网格)
图书馆(公共图书馆)

x我不理解网格中使用的逻辑。括号
,但是如果有一个
bracketsGrob
函数可以简单地返回一个grob而不绘制它,这会有所帮助。可能会向维护人员提出功能请求

无论如何,假设这样一个函数可用,它可以提供给
annotation\u 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)

bracketsGrob一个非常非常晚的答案,我的软件包
lemon
会这样做,虽然不是花括号,而是方括号

这里有一个来自的示例-它们可以被指向外部和内部,请参阅


您可以查看同一问题的答案。这些大括号在导出时没有问题,因为它们基于正常的几何路径。

是的,这是一个更好的答案。这太神奇了。总有一天我必须学习网格/网格操作。一个简化:您不需要在
bracketsGrob
中创建新环境,您可以传递
environment()
。它只包含
l
变量。答案很好,我花了一段时间才弄清楚它,所以对“npc”单位有一点评论(谢谢你在回答中说得很清楚!)。如果要从x、y值开始,则需要按轴缩放它们(因此1=轴的终点,0=轴的起点)。