Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在R中进行堆叠条形图绘制?(包括风险价值的价值)_R_Bar Chart - Fatal编程技术网

如何在R中进行堆叠条形图绘制?(包括风险价值的价值)

如何在R中进行堆叠条形图绘制?(包括风险价值的价值),r,bar-chart,R,Bar Chart,我需要你的帮助。 我试着在R中做一个堆叠的条形图,但我暂时没有成功。我读过好几篇文章,但都没有成功 就像我是新手一样,这是我想要的图表(我用excel制作) 这就是我获得数据的方式 提前感谢您,因此我将使用软件包ggplot2创建此绘图,因为与基本图形软件包相比,定位文本标签更容易: so <- data.frame ( week1= c(1000,950,800), week2=c(1100,10000,850),row.names = c("Q students","student

我需要你的帮助。 我试着在R中做一个堆叠的条形图,但我暂时没有成功。我读过好几篇文章,但都没有成功

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

这就是我获得数据的方式


提前感谢您

,因此我将使用软件包ggplot2创建此绘图,因为与基本图形软件包相比,定位文本标签更容易:

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))
# 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
#首先,我们使用从excel工作表中获取的数据创建一个数据框:
我的数据见