如何在ggplot2中使用facet_wrap获取所有x轴标签,包括缺少的数据?

时间:2016-12-17 09:39:12

标签: r ggplot2

我正在使用更新的ggplot2(2.2.0)。一个很棒的新功能是能够沿着每个x轴绘制不均匀的绘图数量,如this页面所示。​​

我希望在每个方面使用相同的x轴绘图。但是,当引入缺失数据时,这不起作用。作为一个例子,我将利用this问题中的示例数据。

# Example dataset
dataf <- data.frame(x=c(1:30), A=rnorm(30,20,5), B=rnorm(30,15,0.5))
datam <- melt(dataf, id="x")
# Plot in ggplot2
ggplot(datam, aes(factor(x), value)) + 
  geom_bar(stat="identity") + 
  facet_wrap(~variable,nrow = 2,scales = "free")

当我删除特定行并引入缺失数据时(根据下面的代码),我不再为&#34; A&#34;提供相同的x轴标签。和&#34; B&#34;。

# Remove certain rows to introduce missing data
datam <- datam[-c(2, 4, 58), ]

我可以使用scales = fixed绘制缺失值并与底部x轴对齐,尽管我不再为组&#34; A&#34;提供x轴刻度线标记。在方面。

ggplot(datam, aes(factor(x), value)) + 
  geom_bar(stat="identity") + 
  facet_wrap(~variable,nrow = 2,scales = "fixed")

即使缺少数据,如何为每个方面显示完全相同的x轴标签?

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

library(reshape2)
library(ggplot2)
dataf <- data.frame(x=c(1:30), A=rnorm(30,20,5), B=rnorm(30,15,0.5))
datam <- melt(dataf, id="x")
datam2 <- datam[-c(2, 4, 58), ] #mising rows
graph<-ggplot(datam2, aes(factor(x), value)) + 
  geom_bar(stat="identity") + 
  facet_wrap(~variable,nrow = 2,scales = "fixed")
library(gtable)
library(grid)
g <- ggplotGrob(graph) #retrieve grob from graph
panels <- grep("panel", g$layout$name)
top <- unique(g$layout$t[panels])
all <- gtable:::rbind_gtable(gtable:::rbind_gtable(g[seq.int(min(top)), ], 
                                                   g[max(top)+1,], "first"), 
                             g[seq(min(top)+1, nrow(g)),], "first")
grid.newpage()
grid.draw(all)

enter image description here
很确定我在某个时候在SO上找到了一个解决方案。但是不记得原帖。