【问题标题】:Creating group by group plots in r [duplicate]在r中创建分组图[重复]
【发布时间】:2019-07-19 09:47:13
【问题描述】:

如何使用 ggplot 创建集群的分组图,每个集群中都有几个人。

例如:

df <- structure(list(ID = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 
5L, 5L, 6L, 6L), .Label = c("1", "2", "3", "4", "5", "6"), class = "factor"), 
    cluster = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 
    3L, 3L, 3L), .Label = c("1", "2", "3"), class = "factor"), 
    val = c(1.2581800436601, 6.79055672604591, 9.77732860250399, 
    3.60806297743693, 1.14399523707107, 7.9990872181952, 3.16242988454178, 
    5.64627967076376, 8.82345798192546, 4.29119206266478, 8.62997844815254, 
    6.46683012368158), date = c(1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 
    1, 2)), class = "data.frame", row.names = c(NA, -12L))

   ID cluster      val date
1   1       1 1.258180    1
2   1       1 6.790557    2
3   2       1 9.777329    1
4   2       1 3.608063    2
5   3       2 1.143995    1
6   3       2 7.999087    2
7   4       2 3.162430    1
8   4       2 5.646280    2
9   5       3 8.823458    1
10  5       3 4.291192    2
11  6       3 8.629978    1
12  6       3 6.466830    2

我想创建 2x3 图,包含 3 列集群,每个人的每列有 2 行图。

我正在使用的当前代码给出了情节的一般结构,但有很多空白情节:

ggplot(df, aes(date,val)) + geom_bar(stat='identity') + facet_grid(ID~cluster)

【问题讨论】:

  • facet_wrap(~ cluster + ID)
  • @PoGibas:不,因为第一行将包含集群/ID 1/1、1/2 和 2/3,第二行将包含 2/4、3/5 和 3/6。

标签: r ggplot2 plot facet-wrap


【解决方案1】:

要按集群对它们进行分组,您必须在数据中施加正确的顺序。现在,facet_wrap 顺其自然。一种方法是重新排列df,另一种是创建一个虚拟变量(cluster + ID)并按所需顺序排列级别。

那么,您希望 ID 1、3 和 5 在顶行,ID 2、4 和 6 在底行,对吗?这是一种方法:

df$ID <- factor(df$ID, levels=as.character(c(1, 3, 5, 2, 4, 6)))
ggplot(df, aes(date,val)) + geom_bar(stat='identity') +  
  facet_wrap(~ID + cluster, ncol=3)

备注。

  1. 具有数值的因子是危险的。在上面,我对因子水平进行了重新排序。所以现在“3”(ID 3)具有因子级别“3”和数值2。由于 factor 有时会转换为字符串,有时会转换为其数值,这在某些情况下可能会导致混乱。此外,在 facet wrap 图上,您无法区分哪个数字对应于 ID,以及什么对应于集群。

    我的建议是始终使用显式 ID,例如

    df <- df %>% mutate(ID=paste0("ID.", ID), cluster=paste0("CL.", cluster))
    df$ID <- factor(df$ID, levels=paste0("ID.", (c(1, 3, 5, 2, 4, 6))))
    
  2. 上述方法的替代方法是将facet_grid 与虚拟变量一起使用:

    df$row <- factor(rep(rep(c("top", "bottom"), each=2), 3), 
                      levels=c("top", "bottom"))
    ggplot(df, aes(date,val)) + geom_bar(stat='identity') + 
        facet_grid(rows=vars(row), cols=vars(cluster)) +
        theme(strip.text.y = element_blank())
    

【讨论】:

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