How to plot histogram/ frequency-count of a vector with ggplot?

前端 未结 3 1013
无人及你
无人及你 2020-12-19 01:34

I want to plot with ggplot the frequency of values from a numeric vector. With plot() is quite straight forward but I can\'t get the same resul

相关标签:
3条回答
  • 2020-12-19 02:11

    Try the code below

    library(ggplot2)    
    dice_results <- c(1,3,2,4,5,6,5,3,2,1,6,2,6,5,6,4,1,3,2,4,6,4,1,6,3,2,4,3,4,5,6,7,1)
    ggplot() + aes(dice_results)+ geom_histogram(binwidth=1, colour="black", fill="white")
    
    0 讨论(0)
  • 2020-12-19 02:13

    Please look at the help page ?geom_histogram. From the first example you may find that this works.

    qplot(as.factor(dice_results), geom="histogram")
    

    Also look at ?ggplot. You will find that the data has to be a data.frame

    0 讨论(0)
  • 2020-12-19 02:14

    The reason you got an error - is the wrong argument name. If you don't provide argument name explicitly, sequential rule is used - data arg is used for input vector.

    To correct it - use arg name explicitly:

    ggplot(mapping = aes(dice_results)) + geom_bar()
    

    You may use it inside geom_ functions familiy without explicit naming mapping argument since mapping is the first argument unlike in ggplot function case where data is the first function argument.

    ggplot() + geom_bar(aes(dice_results))
    

    Use geom_histogram instead of geom_bar for Histogram plots:

    ggplot() + geom_histogram(aes(dice_results))
    

    Don't forget to use bins = 5 to override default 30 which is not suitable for current case:

    ggplot() + geom_histogram(aes(dice_results), bins = 5)
    
    qplot(dice_results, bins = 5) # `qplot` analog for short
    

    To reproduce base hist plotting logic use breaks args instead to force integer (natural) numbers usage for breaks values:

    qplot(dice_results, breaks = 1:6)
    
    0 讨论(0)
提交回复
热议问题