猿问

R中的堆积条形图

我已经看过关于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

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


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


吃鸡游戏
浏览 849回答 3
3回答

慕仙森

数据集:dat <- read.table(text = "A&nbsp; &nbsp;B&nbsp; &nbsp;C&nbsp; &nbsp;D&nbsp; &nbsp;E&nbsp; &nbsp;F&nbsp; &nbsp; G1 480 780 431 295 670 360&nbsp; 1902 720 350 377 255 340 615&nbsp; 3453 460 480 179 560&nbsp; 60 735 12604 220 240 876 789 820 100&nbsp; &nbsp;75", header = TRUE)现在,您可以将数据框转换为矩阵并使用该barplot函数。barplot(as.matrix(dat))

紫衣仙女

使用ggplot2的方法有些不同:dat <- read.table(text = "A&nbsp; &nbsp;B&nbsp; &nbsp;C&nbsp; &nbsp;D&nbsp; &nbsp;E&nbsp; &nbsp;F&nbsp; &nbsp; G1 480 780 431 295 670 360&nbsp; 1902 720 350 377 255 340 615&nbsp; 3453 460 480 179 560&nbsp; 60 735 12604 220 240 876 789 820 100&nbsp; &nbsp;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)) +&nbsp;&nbsp; geom_bar(stat = "identity") +&nbsp; xlab("\nType") +&nbsp; ylab("Time\n") +&nbsp; guides(fill = FALSE) +&nbsp; theme_bw()这给出了:如果要包含图例,请删除该guides(fill = FALSE)行。

炎炎设计

我显然不是一个很好的R编码器,但是如果您想用ggplot2做到这一点:data<- rbind(c(480, 780, 431, 295, 670, 360,&nbsp; 190),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;c(720, 350, 377, 255, 340, 615,&nbsp; 345),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;c(460, 480, 179, 560,&nbsp; 60, 735, 1260),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;c(220, 240, 876, 789, 820, 100,&nbsp; &nbsp;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&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<- as.data.frame(rbind(a, b, c, d, e, f, g))colnames(data) <-c("Time", "Type", "Group")data$Type&nbsp; &nbsp; &nbsp; <- factor(data$Type, labels = c("A", "B", "C", "D", "E", "F", "G"))library(ggplot2)ggplot(data = data, aes(x = Type, y = Time, fill = Group)) +&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;geom_bar(stat = "identity") +&nbsp; &nbsp; &nbsp; &nbsp;opts(legend.position = "none")
随时随地看视频慕课网APP
我要回答