0

my column in a dataset look like this:

teacher student  
 y        n  
 y        n  
 y        y  
 y        n  
 y        n  
 n        n  
 n        n   
 n        y  
 y        y  
 n        y  
 y        n  

I used

barchart(data$teacher) 

for a graph for teacher, which shows the frequency of y and n in two separate bars, but now I want to show y and n stacked for both variables, so one bar each variable. I tried many things like chart.StackedBar but they all didn't work. Thanks for any help!

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
user2373707
  • 105
  • 1
  • 1
  • 8
  • 1
    Does [this](http://stackoverflow.com/questions/9711067/need-to-create-a-stack-bar-chart) help? Or maybe [this](http://stackoverflow.com/questions/12886572/stacked-bar-plot-for-vectors-that-do-not-have-the-same-size)? – Jilber Urbina Nov 16 '13 at 21:09

2 Answers2

3

Read the man pages, bro. This is what you want:

barplot(matrix(c(table(df$teacher), table(df$student)), ncol=2), 
        col=c('red', 'blue'),  
        names.arg=c('teacher', 'student'), 
        legend.text=c('y', 'n'))
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
Hillary Sanders
  • 5,778
  • 10
  • 33
  • 50
0

EDIT: based on your comment, is this what you are looking for?

library(reshape2)
tmp <- melt(dat, id.vars = NULL)
names(tmp) <- c('Occupation', 'ID')

ggplot(data = tmp, aes(x = Occupation, fill= ID)) + geom_histogram()

enter image description here

ORIGINAL:

I've approached this type of graph using ggplot. Here is a simple example:

library(ggplot2)
set.seed(1618)
dat <- data.frame(teacher = sample(c('y','n'),10,replace=T),
                  student = sample(c('y','n'),10,replace=T))

ggplot(data = dat, aes(x = teacher, fill = student)) + geom_histogram()

enter image description here

You might also consider

ggplot(data = dat, aes(x = teacher, fill = student)) + 
geom_histogram(alpha= .5, position = 'identity')

Which would look like:

enter image description here

If you can't tell, the second graph is just "overlaying" the bars rather than stacking them.

I'm not great at ggplot, but hopefully this helps a bit.

rawr
  • 20,481
  • 4
  • 44
  • 78
  • thanks. but what I want is teacher and student on x-axis instead of n and y, and y-axis(the two colors) for y and n, so I don't really understand your graph... the stacked bar for teacher should show how many of the data are teachers and how many not – user2373707 Nov 16 '13 at 21:48