【问题标题】:R and ggplot: Putting x-axis labels outside the panel in ggplotR和ggplot:将x轴标签放在ggplot的面板外
【发布时间】:2017-07-26 18:25:03
【问题描述】:

有没有办法将标签相对于 ggplot 中的绘图面板向前移动? 实际上我试图回答我的问题here。尽管我认为在 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')

【问题讨论】:

  • 我不确定您的问题是关于@lukeA 在下面回答的剪辑,还是您在询问是否在情节之外进行注释。如果是后者,这提供了一个答案:stackoverflow.com/questions/12409960/…
  • 正如我在帖子中提到的,这是试图回答我的另一个问题 - stackoverflow.com/questions/42595256/…。我需要沿 x 轴放置自定义 x 轴标签,而不在所有 facet_subplots 中重复它们

标签: r ggplot2 geom-text


【解决方案1】:

您必须关闭底部面板元素的剪辑:

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) 

Point clipped on x-axis in ggplot

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多