簡體   English   中英

將花括號添加到 ggplot2 然后使用 ggsave

[英]Add curly braces to ggplot2 and then use ggsave

所以這與這個問題非常相關,這個答案是一個很好的解決方案。

問題是當我嘗試使用 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 保存它。

我不明白grid.brackets使用的邏輯,但如果有一個bracketsGrob grid.brackets函數,它會簡單地返回一個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)

在此處輸入圖片說明

好吧,我想你可以用設備做一些事情,作為ggsave的替代ggsave ,我終於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()

圖片: 在此處輸入圖片說明

屬性:

在此處輸入圖片說明

一個非常非常晚的答案,我的包裝lemon做到了這一點,盡管不是花括號,而是方括號。

這是小插圖中的一個示例 - 它們可以向外和向內定向,請參見https://cran.r-project.org/package=lemon

在此處輸入圖片說明

您可以查看this answer to the same question。 這些大括號沒有導出問題,因為它們基於正常的 geom_path。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM