【问题标题】:How to have all x-axis labels, including missing data, in ggplot2 with facet_wrap?如何在带有 facet_wrap 的 ggplot2 中拥有所有 x 轴标签,包括缺失的数据?
【发布时间】:2016-12-17 09:39:11
【问题描述】:

我正在使用更新的 ggplot2 (2.2.0)。根据this 页面,一个很棒的新功能是能够沿每个 x 轴绘制奇数数量的图。

我希望在每个方面使用相同的 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")

当我删除特定行并引入缺失数据时(根据我下面的代码),我不再为“A”和“B”使用相同的 x 轴标签。

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

我可以使用 scales = fixed 绘制缺失值并与底部 x 轴对齐,尽管我不再在构面中为组“A”提供 x 轴刻度标记标签。

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

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

谢谢。

【问题讨论】:

  • @hadley - ggplot2 中是否有功能可以在不使用以下答案中的解决方法的情况下执行上述操作?
  • 我只在 ggplot2 功能中提供了以下解决方案,没有解决方法。

标签: r ggplot2


【解决方案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)


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

【讨论】:

  • 太好了,感谢您的解决方法!遗憾的是,它无法通过 scales 选项解决。我将如何添加我的 y 轴标签(不在原始帖子中)?
【解决方案2】:

这是一个仅使用 ggplot2 功能的解决方案。 scale_x_discreet' and scale_y_discreet' 中有一个drop 参数,当设置为FALSE 时,它会显示所有因子,无论该因子是否存在数据。

? scale_x_discreet。第一步是分解datam$x

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")

# missing data
datam <- datam[-c(2, 4, 58), ]

# solution
ggplot(datam, aes(factor(x), value)) + 
  geom_bar(stat="identity") + 
  facet_wrap(~variable,nrow = 2, scales = "free") + 
  scale_x_discrete(drop=FALSE)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 2018-05-19
    • 1970-01-01
    • 2015-09-22
    相关资源
    最近更新 更多