R中ggplot2的不同类别直方图

时间:2015-04-11 21:03:00

标签: r ggplot2 reshape2

这是我的代码:

set.seed(0)
practice<-matrix(c(c("class1","class2","class3","class4","class5","class6"),sample(1:100,30)),ncol=6)
colnames(practice)<-c("classes","Strongly_Agree","Somewhat_Agree","Somewhat_Disagree",
        "Strongly_Disagree","No_Idea")
data<-as.data.frame(practice)
require(ggplot2)
require(reshape2)
new_data<-melt(data,id.vars=c("classes"))
graph<-ggplot(new_data,aes(x = variable, y=..density..,fill=variable)) 
graph<-graph+facet_wrap(~classes,scales = "free_y")
graph+geom_histogram()

Graph I got

除了我想知道为什么直方图具有相同的长度之外,一切看起来都是正确的。我想要的是显示六个班级中具有不同意见的学生的百分比(x轴:非常同意,有些同意....,y轴:不同人群的百分比)。我需要为代码添加什么?扩展

非常感谢你!

1 个答案:

答案 0 :(得分:0)

这与问题无关,但很高兴知道:矩阵和向量只能有一种类型的值。您尝试使用字符和数字创建样本矩阵。我会尝试按照您的步骤进行操作,但在此处更正一两个:

set.seed(0)
# lets create values only (we will add names later in a data frame)
practice <- matrix(sample(1:100, 30), ncol = 5)
data <- as.data.frame(practice)
data <- cbind( classes = sprintf("class%d", 1:6), data)
names(data) <- c("classes", "Strongly_Agree", "Somewhat_Agree", "Somewhat_Disagree", "Strongly_Disagree","No_Idea")

现在你可以计算百分比(用行和除以每一行; [,-1] 这里是为了省略第一列 - ,它们不包含数字):

data[,-1] <- data[,-1] / rowSums(data[,-1])

在这里,我没有做任何改变:

require(reshape2)
new_data <- melt(data, id.vars = c("classes"))

在ggplot部分中,您可以使用new_data中的value列和普通geom_bar(因为我们已经计算了值):

require(ggplot2)

graph <- ggplot(new_data, aes(x = variable, y = value, fill = variable)) 
graph <- graph + facet_wrap(~classes, scales = "free_y")
graph + geom_bar(stat = "identity")

enter image description here