17

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?

0

3 Answers 3

32

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")
Sign up to request clarification or add additional context in comments.

1 Comment

The answer doesn't actually explain why it works. Could this be added, since it is the highest voted?
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

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.