2016-02-25 108 views
3

所以這是這個question非常相關的,這是answer一個很好的解決方案。 的問題是,當我嘗試使用ggsave出口的情節大括號不存在。添加大括號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) 

我不開放使用RStudio導出按鈕,因爲它不正確地導出我的主題,字體大小等。我還需要超過76 dpi的分辨率更高。我需要一個解決方案來將大括號添加到ggplot2圖形,並能夠使用ggsave進行保存。

回答

5

我不不懂在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) 

enter image description here

+0

是的,這是一個更好的答案。 –

+0

這真了不起。其中一天,我必須學習grid/grob操作。一種簡化:你不需要在'bracketsGrob'中創建一個新的環境,你可以傳遞'environment()'。無論如何,它只包含'l'變量。 –

1

那麼我想你可以做一些設備,以替代ggsave,我終於得到了這個工作。這是更多的努力比它應該是,因爲R-Studio中不知何故無法瞭解哪些設備實際上是打開或關閉(OFF)。所以你必須有時重置你的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() 

的圖像: enter image description here

性能:

enter image description here

+1

Awesomesauce!謝謝 – SamanthaDS