首页 文章

R中的堆积条形图

提问于
浏览
27

我已经看过这里有关R中堆积条形图的类似问题,但我仍然没有运气 .

我创建了以下数据框:

A   B   C   D   E   F    G
     1 480 780 431 295 670 360  190
     2 720 350 377 255 340 615  345
     3 460 480 179 560  60 735 1260
     4 220 240 876 789 820 100   75

答:G代表x轴,y轴代表持续时间(秒) . 我如何在R中堆叠以下数据?

非常感谢您的时间和帮助 .

3 回答

  • 39

    数据集:

    dat <- read.table(text = "A   B   C   D   E   F    G
    1 480 780 431 295 670 360  190
    2 720 350 377 255 340 615  345
    3 460 480 179 560  60 735 1260
    4 220 240 876 789 820 100   75", header = TRUE)
    

    现在,您可以将数据帧转换为矩阵并使用 barplot 函数 .

    barplot(as.matrix(dat))
    

    enter image description here

  • 6

    使用ggplot2的方法有点不同:

    dat <- read.table(text = "A   B   C   D   E   F    G
    1 480 780 431 295 670 360  190
    2 720 350 377 255 340 615  345
    3 460 480 179 560  60 735 1260
    4 220 240 876 789 820 100   75", header = TRUE)
    
    library(reshape2)
    
    dat$row <- seq_len(nrow(dat))
    dat2 <- melt(dat, id.vars = "row")
    
    library(ggplot2)
    
    ggplot(dat2, aes(x = variable, y = value, fill = row)) + 
      geom_bar(stat = "identity") +
      xlab("\nType") +
      ylab("Time\n") +
      guides(fill = FALSE) +
      theme_bw()
    

    这给了:

    enter image description here

    如果要包含图例,请删除 guides(fill = FALSE) 行 .

  • 25

    我显然不是一个非常好的R编码器,但如果你想用ggplot2做这个:

    data<- rbind(c(480, 780, 431, 295, 670, 360,  190),
                 c(720, 350, 377, 255, 340, 615,  345),
                 c(460, 480, 179, 560,  60, 735, 1260),
                 c(220, 240, 876, 789, 820, 100,   75))
    
    a <- cbind(data[, 1], 1, c(1:4))
    b <- cbind(data[, 2], 2, c(1:4))
    c <- cbind(data[, 3], 3, c(1:4))
    d <- cbind(data[, 4], 4, c(1:4))
    e <- cbind(data[, 5], 5, c(1:4))
    f <- cbind(data[, 6], 6, c(1:4))
    g <- cbind(data[, 7], 7, c(1:4))
    
    data           <- as.data.frame(rbind(a, b, c, d, e, f, g))
    colnames(data) <-c("Time", "Type", "Group")
    data$Type      <- factor(data$Type, labels = c("A", "B", "C", "D", "E", "F", "G"))
    
    library(ggplot2)
    
    ggplot(data = data, aes(x = Type, y = Time, fill = Group)) + 
           geom_bar(stat = "identity") +
           opts(legend.position = "none")
    

    enter image description here

相关问题