Make Frequency Histogram for Factor Variables

后端 未结 6 1445
野趣味
野趣味 2020-12-01 03:15

I am very new to R, so I apologize for such a basic question. I spent an hour googling this issue, but couldn\'t find a solution.

Say I have some categorical data in

6条回答
  •  旧时难觅i
    2020-12-01 04:06

    The reason you are getting the unexpected result is that hist(...) calculates the distribution from a numeric vector. In your code, table(animalFactor) behaves like a numeric vector with three elements: 1, 3, 7. So hist(...) plots the number of 1's (1), the number of 3's (1), and the number of 7's (1). @Roland's solution is the simplest.

    Here's a way to do this using ggplot:

    library(ggplot2)
    ggp <- ggplot(data.frame(animals),aes(x=animals))
    # counts
    ggp + geom_histogram(fill="lightgreen")
    # proportion
    ggp + geom_histogram(fill="lightblue",aes(y=..count../sum(..count..)))
    

    You would get precisely the same result using animalFactor instead of animals in the code above.

提交回复
热议问题