Question

I have a data structure, and I need to graph the dyads by the variables in one column and the variables in another. For example, say I have a survey and one column is about how students feel about a class with "strongly agree", "agree", "neutral", "disagree", and "strongly disagree" as options. On another column I have the grade levels of those who took the survey. How would I sort out and graph this data so that I can have show how many people in one grade said "strongly agree", how many in one grade said "agree", etc. for all the grades?

Example data:

set.seed(123)
feelops <- c("strongly agree", "agree", "neutral", "disagree", "strongly disagree")
feelops <- ordered(feelops,levels=feelops)
dat <- data.frame(feel=sample(feelops,100,replace=TRUE) , grade=sample(LETTERS[1:5],100,replace=TRUE))

> head(dat)
               feel grade
1             agree     C
2          disagree     B
3           neutral     C
4 strongly disagree     E
5 strongly disagree     C
6    strongly agree     E
Was it helpful?

Solution

Using a barplot and the example data, something like this might work:

barplot(
  with(dat,prop.table(table(feel,grade))),
  beside=TRUE,
  xlab="Grade",
  ylab="% Feeling Within Grade Group",
  col=grey((1:5)/5)
)
legend("topright",as.character(feelops),fill=grey(1:5/5))

You can play around with the options a bit, but this will give something like:

enter image description here

OTHER TIPS

Another option is to use higher level plot packages like ggplot2 or lattice. They are much flexible than the base package. Here I am using barchart to create 2 version of barplots. The second one use reshape2 to put data in longer format generally more suitable for such plots.

library(lattice) 
library(reshape2)
library(gridExtra)

dat1 <- with(dat,prop.table(table(grade,feel)))
p1 <- barchart(dat1, groups=0)
dat.m <- melt(dat1)
p2 <- barchart(value~grade,groups=feel,data= dat.m, auto.key=TRUE)
grid.arrange(p1,p2)

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top