R中的堆积条形图

Stacked Bar Graph In R

所以我正在尝试制作堆积条形图。这是图中需要的所有数据。我想让 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")

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

你想要这个吗?

# Your original data
data %>%
  # Number should be numeric
  mutate(Number = as.numeric(Number),
         # Groups ('a-e' or 'f-j') aren't in the data
         # so I am randomly generating them here
         Group = sample(c('a-e', 'f-j'), n(), replace = TRUE)) %>%
  # I assume you want one (overall) value per year, age, and group ('a-e' or 'f-j')
  group_by(Year, Age, Group) %>%
  # So we get the sum of number
  summarise(Number = sum(Number)) %>%
  # And make the plot
  ggplot(aes(x = Year, y = Number, fill = Age, group = Group)) + 
  geom_bar(stat = 'identity', position = 'dodge', width = 0.9)

您需要 dodge 您在 ggplot2 中的位置,如下所示:

数据:

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

绘图:

library(ggplot2)


ggplot(data = data, aes(x = Age , y = as.numeric(Number), fill = Year)) + 
  geom_bar(stat = "identity",position="dodge") + facet_grid(~Group)

?ggplot2::position_dodge

Dodging preserves the vertical position of an geom while adjusting the horizontal position.

输出:

听起来你不想将年份、年龄组合并...所以我创建了另一个变量来将它们分开,然后使用 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")