简体   繁体   中英

Different category histograms with ggplot2 in R

Here is my code:

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()

我得到的图

Everything looks right except that I wonder why the histograms have the same length. What I want is to show the percentage of students with different opinions in the six classes (x-axis:strongly agree, somewhat agree....,y-axis:the percentage of different groups of people). What else I need to add for the code? scale?

Thank you so much!

It is not related to the question, but it is good to know: matrices and vectors can only have one type of values. You tried to create your sample matrix with characters and numbers. I will try to follow your steps but correct one or two here:

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")

Now you can calculate percentages (divide every row with row sum; the [,-1] is here for omitting the first column - classes that doesn't hold the numbers):

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

Here I didn't change anything:

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

In the ggplot part you can use value column from your new_data and ordinary geom_bar (as we already calculated the values):

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")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM