[英]R and ggplot: Putting x-axis labels outside the panel in ggplot
Is there a way to bring the labels forward with respect to plot panel in ggplot? 有没有一种方法可以使标签相对于ggplot中的绘图面板向前移动? Actually I was trying to answer my question here . 实际上,我试图在这里回答我的问题。 I have not got any satisfactory response to that one although I thought it would be possible in ggplot. 尽管我认为可以在ggplot中实现,但是对此我没有任何满意的答复。 This is an attempt to get a solution although a hacky one. 这是一种试图获得解决方案的尝试,尽管该解决方案很笨拙。 But the labels are rendered below the plot panel here. 但是标签将显示在此处的情节面板下方。
Following are my (example) data, attempted solution and the resulting plot. 以下是我的(示例)数据,尝试的解决方案和结果图。
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')
You have to turn off clipping of the bottom panel elements: 您必须关闭底部面板元素的裁剪:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.