【问题标题】:Plot classified by categories with column-names (R)按具有列名 (R) 的类别分类的图
【发布时间】:2021-09-07 12:14:36
【问题描述】:

我有一个拥有下一个结构的数据框:

D1A1    D1A2    D1A3    D1B1    D1B2    D1B3    D2A1    D2A2    D2A3    D2B1    D2B2    D2B3
 10      12      15      40      39      27      11      13      14      33      31      32

实际数据框的维度更大(40 个观察值/列)。我的兴趣是创建任何可能的图表,显示所有数字信息以及按列分类(D1A、D1B、D2A、D2B)聚类的数据,如下所示:

               D1A1+D1A2+D1A3 || D1B1+D1B2+D1B3 || D2A1+D2A2+D2A3 || D2B1+D2B2+D2B3

只要我感到非常失落,任何建议都将不胜感激。

【问题讨论】:

  • 当您有超过 1 行时,您是否打算按行和列获取 D1A1, D1A2, D1A3 的总和(对于其他列类似)
  • 如果您创建一个小的可重现示例以及预期的输出,这将更容易提供帮助。阅读how to give a reproducible example

标签: r plot boxplot


【解决方案1】:

我们可以通过列名的子字符串拆分数据集,遍历list并获取rowSums并使用barplot

out <- sapply(split.default(df1, sub("\\d+$", "", names(df1))), 
             rowSums, na.rm = TRUE)
barplot(out)

如果有更多行并且想要绘制,请使用tidyverse,我们可以通过使用列名中的模式,即捕获不带数字的列名的子字符串,使用pivot_longer 重塑为“长”格式结束。这将创建 4 列。然后,我们使用summariseacross 来获取每列的sum 并返回一个条形图 - geom_col

library(dplyr)
library(tidyr)
library(ggplot2)
df2 %>% 
    pivot_longer(cols = everything(), names_to = ".value", 
        names_pattern = "(.*)\\d+$") %>% 
    summarise(across(everything(), sum, na.rm = TRUE)) %>% 
    pivot_longer(cols = everything()) %>% 
   ggplot(aes(x = name, y = value, fill = name)) + 
      geom_col()

-输出


如果我们对数据的传播感兴趣,箱线图可以提供帮助。在这里,我们不用summarise,而是用geom_boxplot代替geom_col

 df2 %>%
     pivot_longer(cols = everything(), names_to = ".value", 
          names_pattern = "(.*)\\d+$") %>%
     pivot_longer(cols = everything()) %>%
     ggplot(aes(x = name, y = value, fill = name)) + 
        geom_boxplot()

数据

df1 <- structure(list(D1A1 = 10L, D1A2 = 12L, D1A3 = 15L, D1B1 = 40L, 
    D1B2 = 39L, D1B3 = 27L, D2A1 = 11L, D2A2 = 13L, D2A3 = 14L, 
    D2B1 = 33L, D2B2 = 31L, D2B3 = 32L), class = "data.frame", row.names = c(NA, 
-1L))

df2 <- structure(list(D1A1 = c(10L, 15L), D1A2 = c(12L, 23L), D1A3 = 15:14, 
    D1B1 = c(40L, 23L), D1B2 = c(39L, 14L), D1B3 = c(27L, 22L
    ), D2A1 = 11:10, D2A2 = c(13L, 15L), D2A3 = c(14L, 17L), 
    D2B1 = c(33L, 35L), D2B2 = c(31L, 35L), D2B3 = c(32L, 32L
    )), class = "data.frame", row.names = c(NA, -2L))

【讨论】:

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