2017-07-17 47 views
1

之間裁剪線說我有一個情節是這樣的:ggplot:面

# Load libraries 
library(ggplot2) 
library(grid) 

# Load data 
data(mtcars) 

# Plot results 
p <- ggplot(data = mtcars) 
p <- p + geom_bar(aes(cyl)) 
p <- p + coord_flip() 
p <- p + facet_wrap(~am) 

print(p) 

enter image description here

現在,我想在這兩個方面在酒吧情節主線一路。我補充一點:

p <- p + geom_vline(aes(xintercept = cyl)) 

enter image description here

它增加了線,但他們不越過這兩個方面。因此,我嘗試使用此解決方案關閉剪輯:

# Turn off clipping 
gt <- ggplot_gtable(ggplot_build(p)) 
gt$layout$clip[gt$layout$name == "panel"] <- "off" 

# Plot results 
grid.draw(gt) 

但這並不能解決問題:行仍然被剪切。所以,我想知道這是否是特定於geom_vline,並試圖與geom_ablinegeom_line(後者的值在±Inf之間)接近,但結果是相同的。在其他文章中,裁剪解決方案似乎適用於文本和點,但大概在這種情況下,線條僅在圖的範圍內定義。 (我甚至嘗試過gt$layout$clip <- "off"關閉所有可能的剪輯,但這並沒有解決問題。)是否有解決方法?

+2

是否[此答案](https://stackoverflow.com/a/31691313/496488)做你需要什麼? – eipi10

+0

它看起來確實如此。謝謝!顯然我今天特別弱Google Fu ... – Lyngbakr

+0

其實,這段代碼似乎不適合我(或者幾個小時前發佈的其他人)。任何人都可以成功地運行它嗎? – Lyngbakr

回答

0
library(grid) 
library(gtable) 

# Starting from your plot `p` 
gb <- ggplot_build(p) 
g <- ggplot_gtable(gb) 

# Get position of y-axis tick marks 
ys <- gb$layout$panel_ranges[[1]][["y.major"]] 


# Add segments at these positions 
# subset `ys` if you only want to add a few 
# have a look at g$layout for relevant `l` and `r` positions 
g <- gtable_add_grob(g, segmentsGrob(y0=ys, y1=ys, 
            gp=gpar(col="red", lty="dashed")), 
        t = 7, l = 4, r=8) 

grid.newpage() 
grid.draw(g) 

請參閱ggplot, drawing multiple lines across facets瞭解如何重新縮放數值以獲得更一般的繪圖。即

data2npc <- function(x, panel = 1L, axis = "x") { 
    range <- pb$layout$panel_ranges[[panel]][[paste0(axis,".range")]] 
    scales::rescale(c(range, x), c(0,1))[-c(1,2)] 
} 

start <- sapply(c(4,6,8), data2npc, panel=1, axis="y") 

g <- gtable_add_grob(g, segmentsGrob(y0=start, y1=start), 
         t=7, r=4, l=8)