2017-03-06 128 views
0

有沒有一種方法可以使標籤在ggplot中相對於繪圖面板向前? 其實我試圖回答我的問題here。我沒有得到任何令人滿意的答覆,但我認爲這將是可能的ggplot。這是一個嘗試獲得解決方案,儘管是一個黑客。但標籤在這裏顯示在繪圖面板下方。R和ggplot:將x軸標籤放在ggplot的面板之外

以下是我的(示例)數據,嘗試解決方案和結果圖。

library(ggplot2) 
library(magrittr)  
mydata = data.frame(expand.grid(Tag = c('A','B','C'),Year = 2010:2011,PNo = paste0("X-",1:4)),Value = round(runif(24,1,20))) 
mydata$dist = ifelse(mydata$Tag == 'A',0,ifelse(mydata$Tag=='B',2,7)) 

mydata %>% ggplot(aes(x = dist,y = Value,fill = factor(Year))) +geom_bar(stat='summary',position = 'dodge',fun.y='mean',width = 1) + 
    facet_wrap(~PNo,ncol=2) + 
    theme(axis.text.x = element_blank(),axis.ticks.x = element_blank()) + 
    geom_label(data = mydata %>% filter(PNo %in% c('X-3','X-4')),aes(x = dist,y=0,label = Tag),size=6,inherit.aes=F,color = 'red') 

enter image description here

+0

我不知道,如果你的問題是關於剪輯@lukeA在下面回答,或者如果你正在詢問關於情節以外的註釋。如果以後,這提供了一個答案:http://stackoverflow.com/questions/12409960/ggplot2-annotate-outside-of-plot – Djork

+0

正如我在後文中提到的這是一個嘗試回答我的另一個問題 - http://stackoverflow.com/questions/42595256/positioning-x-axis-text-label-along-x-axis-based-on-another-field-in-the-data-us。我需要沿x軸放置自定義x軸標籤,而不是在所有facet_subplots中重複它們 –

回答

2

你必須關閉底部面板元素剪裁:

p <- mydata %>% ggplot(aes(x = dist,y = Value,fill = factor(Year))) +geom_bar(stat='summary',position = 'dodge',fun.y='mean',width = 1) + 
    facet_wrap(~PNo,ncol=2) + 
    theme(axis.text.x = element_blank(),axis.ticks.x = element_blank()) + 
    geom_label(data = mydata %>% dplyr::filter(PNo %in% c('X-3','X-4')),aes(x = dist,y=0,label = Tag),size=6,inherit.aes=F,color = 'red') 
library(grid) 
gt <- ggplot_gtable(ggplot_build(p)) 
gt$layout$clip[grep("panel-2-\\d+", gt$layout$name)] <- "off" 
grid.draw(gt) 

enter image description here

Point clipped on x-axis in ggplot