ggplot2 bar plot with two categorical variables

前端 未结 2 1949
时光说笑
时光说笑 2020-12-29 14:16

Suppose I have the following data:

Fruit <- c(rep(\"Apple\",3),rep(\"Orange\",5))
Bug <- c(\"worm\",\"spider\",\"spider\",\"worm\",\"worm\",\"worm\",\"         


        
相关标签:
2条回答
  • 2020-12-29 14:44
    Fruit <- c(rep("Apple",3),rep("Orange",5))
    Bug <- c("worm","spider","spider","worm","worm","worm","worm","spider")
    
    df <- data.frame(Fruit,Bug)
    
    ggplot(df, aes(Fruit, ..count..)) + geom_bar(aes(fill = Bug), position = "dodge")
    

    enter image description here

    0 讨论(0)
  • 2020-12-29 14:51

    This is pretty easy to do with a two way table:

    dat <- data.frame(table(df$Fruit,df$Bug))
    names(dat) <- c("Fruit","Bug","Count")
    
    ggplot(data=dat, aes(x=Fruit, y=Count, fill=Bug)) + geom_bar(stat="identity")
    

    enter image description here

    0 讨论(0)
提交回复
热议问题