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

≯℡__Kan透↙ 提交于 2019-11-29 13:52:16

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

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")

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!