如何在R中堆叠条形图? (包括var的值)

时间:2016-10-31 16:08:33

标签: r bar-chart

我需要你的帮助。 我试图在R中做一个堆积条形图,我暂时没有成功。我已经阅读了几篇文章但是没有成功。

就像我是新手一样,这是我想要的图表(我在excel中制作)

enter image description here

这就是我拥有数据的方式

enter image description here

提前谢谢

2 个答案:

答案 0 :(得分:0)

so <- data.frame ( week1= c(1000,950,800), week2=c(1100,10000,850),row.names = c("Q students","students with Activity","average debt per student")


barplot(as.matrix(so))

答案 1 :(得分:0)

我会使用ggplot2包来创建这个图,因为与基本图形包相比,它更容易定位文本标签:

# First we create a dataframe using the data taken from your excel sheet:
myData <- data.frame(
      Q_students = c(1000,1100),
      Students_with_activity = c(950, 10000),
      Average_debt_per_student = c(800, 850),
      Week = c(1,2))

# The data in the dataframe above is in 'wide' format, to use ggplot
# we need to use the tidyr package to convert it to 'long' format.
library(tidyr)
myData <- gather(myData,
                    Condition,
                    Value,
                    Q_students:Average_debt_per_student)


# To add the text labels we calculate the midpoint of each bar and
# add this as a column to our dataframe using the package dplyr:
library(dplyr)
myData <- group_by(myData,Week) %>%
   mutate(pos = cumsum(Value) - (0.5 * Value))

#We pass the dataframe to ggplot2 and then add the text labels using the positions which
#we calculated above to place the labels correctly halfway down each
#column using geom_text.

library(ggplot2)
# plot bars and add text
p <- ggplot(myData, aes(x = Week, y = Value)) +
  geom_bar(aes(fill = Condition),stat="identity") +
  geom_text(aes(label = Value, y = pos), size = 3)

#Add title
p <- p + ggtitle("My Plot")

#Plot p
p

Example of output