Search code examples
rggplot2bar-chartdata-analysis

R: How to create a barplot from a multi-column frequency data?


Assume I have a dataset as follows,

ID     Class
a      Class_1
a      Class_1
b      Class_1
b      Class_1
b      Class_1

c      Class_2
c      Class_2
c      Class_2
d      Class_2
d      Class_2
d      Class_2

e      Class_3
f      Class_3

I want to show, there are 2 Students in Class_1, 2 Students in Class_2 and 2 Students in Class_3 on a barchart using ggplot()

I appreciate your time. Thank you.


Solution

  • d <- data.frame(ID = c(letters[c(1,1,2,2,2,3,3,3,4,4,4,5,6)]), 
                Class = c(rep("Class_1", 5), rep("Class_2", 6), "Class_3", "Class_3"))
    

    if you want to show the information of the factor's number

    p <- ggplot(d, aes (x = Class, fill = ID) ) + geom_bar(position="fill")
    plot(p)    # check the number of breaks and use it as length
    p + scale_y_continuous(label=seq(0, 2, length=5))
    # Hoom, something strange ?
    

    needn't

    ggplot(d[! duplicated(d),], aes (x = Class, fill = ID) ) + geom_bar()
    

    plot plot