ggplot2 facets作为facet的摘要图

时间:2017-03-30 10:36:19

标签: r plot ggplot2 facet-wrap

通常我们会根据变量生成分面来分解数据,但我们仍然希望将摘要视为一个方面的堆栈。这是一个例子:

library(ggplot2)
ggplot(data=iris, aes(x=Sepal.Length,y=Petal.Length)) +
    geom_point(aes(color=Species)) +
    facet_wrap(~Species, ncol=2)

facet plot of iris data

但是,我还希望其中一个方面是3个方面的叠加:

ggplot(data=iris, aes(x=Sepal.Length,y=Petal.Length)) +
    geom_point(aes(color=Species)) 

this plot to be added as a fourth panel on the previous facet plot

有没有这么容易做到这一点?

非常感谢,

1 个答案:

答案 0 :(得分:0)

我编写了以下函数来复制数据集,并在变量all下的数据下创建一个额外的副本。

library(ggplot2)

# Create an additional set of data    
CreateAllFacet <- function(df, col){
  df$facet <- df[[col]]
  temp <- df
  temp$facet <- "all"
  return(rbind(temp, df))
}

该函数不是覆盖原始构面数据列,而是创建一个名为facet的新列。这样做的好处是我们可以使用原始列来指定绘图点的美学。

df <- CreateAllFacet(iris, "Species")

ggplot(data=df, aes(x=Sepal.Length,y=Petal.Length)) +
  geom_point(aes(color=Species)) +
  facet_wrap(~facet, ncol=2)

enter image description here

在这种情况下,我觉得这个图例是可选的,因为它很大程度上复制了图中已有的信息。可以使用额外的行+ theme(legend.position = "none")

轻松隐藏它