r - R 中的堆叠条形图

标签 r ggplot2 bar-chart boxplot stacked-chart

所以我正在尝试制作一个堆积条形图。这是图中需要的所有数据。我希望 a-e 位于 f-j 旁边。我也试图让 y 轴变得合理。由于某种原因,它用数字而不是限制。我可能做得完全错误。我看过

data<- rbind(c(4655, 4212, 3838, 3583, 3124, 3078, 1411, 2589, 2524, 2429),
         c(2826, 2589, 2557, 2713, 2497, 1, 2, 66, 1757, 1822))

a <- cbind(data[, 1], 1, c("50-60", "40-49"))
b <- cbind(data[, 2], 2, c("50-60", "40-49"))
c <- cbind(data[, 3], 3, c("50-60", "40-49"))
d <- cbind(data[, 4], 4, c("50-60", "40-49"))
e <- cbind(data[, 5], 5, c("50-60", "40-49"))
f <- cbind(data[, 6], 1, c("50-60", "40-49"))
g <- cbind(data[, 7], 2, c("50-60", "40-49"))
h <- cbind(data[, 8], 3, c("50-60", "40-49")) 
i <- cbind(data[, 9], 4, c("50-60", "40-49"))
j <- cbind(data[, 10], 5, c("50-60", "40-49"))

data  <- as.data.frame(rbind(a, b, c, d, e, f, g, h, i, j))
colnames(data) <-c("Number", "Year", "Age")
data$Year      <- factor(data$Year, labels = c("FY13", 
                         "FY14","FY15","FY16","FY17"))

library(ggplot2)

ggplot(data = data, aes(x = data$Year, y = Number, fill = Age)) + 
       geom_bar(stat = "identity")

我可能做得完全错误。我看了又看,但找不到其他可以帮助我的东西。

最佳答案

听起来您不希望将年份、年龄组合并...所以我创建了另一个变量来将它们分开,然后使用facet_grid:

data <- data.frame(as.vector(data), rep(rep(1:5, each=2),2), c("50-60","40-49"), rep(c("Grp1","Grp2"), each=10))

#data  <- as.data.frame(rbind(a, b, c, d, e, f, g, h, i, j))
colnames(data) <-c("Number", "Year", "Age", "Grp")
data$Year      <- factor(data$Year, labels = c("FY13", 
                                               "FY14","FY15","FY16","FY17"))

library(ggplot2)

ggplot(data = data, aes(x = Grp, y = Number, fill = Age)) + facet_grid(~Year) + 
  geom_bar(stat = "identity")

enter image description here

关于r - R 中的堆叠条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44028039/

相关文章:

r - 检测字符串中的非 ascii 字符

r - 多个用户可以同时访问一个开源的 Shiny Server 吗?

r - R中同一张图上的频率和累积频率曲线

rotation - matplotlib:直方图和bin标签

string - 如何将子功能应用于数据框?

r - 为什么sapply返回需要转置的矩阵,然后转置的矩阵将不会附加到数据帧?

r - 用 hexSticker 修剪六边形形状?

r - lapply 函数在 Ggplot 中创建许多图

r - 在 Plotly R 中为条形图添加注释

r - 更改 ggplot2 中的 Y 轴中断