16

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 result with ggplot.

library(ggplot2)    
dice_results <- c(1,3,2,4,5,6,5,3,2,1,6,2,6,5,6,4)    
hist(dice_results)

enter image description here

ggplot(dice_results) + geom_bar()
# Error: ggplot2 doesn't know how to deal with data of class numeric

Should I create a dataframe for ggplot() to plot my vector?

smci
  • 32,567
  • 20
  • 113
  • 146
CptNemo
  • 6,455
  • 16
  • 58
  • 107

3 Answers3

31

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")
Stas Prihod'co
  • 864
  • 9
  • 13
8

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

shadow
  • 21,823
  • 4
  • 63
  • 77
7

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)
George Shimanovsky
  • 1,668
  • 1
  • 17
  • 15