简体   繁体   English

R中的堆积条形图

[英]Stacked Bar Plot in R

I've looked at the similar questions on here regarding stacked bar plots in R, but I'm still not having any luck. 我已经看过关于R中堆积条形图的类似问题,但是我仍然没有运气。

I have created the following data frame: 我创建了以下数据框:

        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 represents the x-axis and the y-axis would be duration (seconds). A:G代表x轴,y轴为持续时间(秒)。 How would I go about stacking the following data in R? 我将如何在R中堆叠以下数据?

Thank you very much in advance for your time and help. 非常感谢您的时间和帮助。

The dataset: 数据集:

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)

Now you can convert the data frame into a matrix and use the barplot function. 现在,您可以将数据帧转换为矩阵并使用barplot函数。

barplot(as.matrix(dat))

在此处输入图片说明

A somewhat different approach using ggplot2: 使用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()

this gives: 这给出了:

在此处输入图片说明

When you want to include a legend, delete the guides(fill = FALSE) line. 当您要包含图例时,请删除参考线guides(fill = FALSE)

I'm obviosly not a very good R coder, but if you wanted to do this with ggplot2: 我显然不是一个很好的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")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM