为了账号安全,请及时绑定邮箱和手机立即绑定

R中的堆积条形图

R中的堆积条形图

吃鸡游戏 2019-12-04 10:00:23
我已经看过关于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   75A:G代表x轴,y轴为持续时间(秒)。我将如何在R中堆叠以下数据?非常感谢您的时间和帮助。
查看完整描述

3 回答

?
慕仙森

TA贡献1827条经验 获得超7个赞

数据集:


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))


查看完整回答
反对 回复 2019-12-04
?
紫衣仙女

TA贡献1839条经验 获得超15个赞

使用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()

这给出了:


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


查看完整回答
反对 回复 2019-12-04
?
炎炎设计

TA贡献1808条经验 获得超4个赞

我显然不是一个很好的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")


查看完整回答
反对 回复 2019-12-04
  • 3 回答
  • 0 关注
  • 807 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信