Reputation: 161
i want to plot a histogram by ggplot 2 from a vector. the dataset is rivers from datasets packages
rivers
[1] 735 320 325 392 524 450 1459 135 465 600 330 336 280 315 870 906 202 329
[19] 290 1000 600 505 1450 840 1243 890 350 407 286 280 525 720 390 250 327 230
[37] 265 850 210 630 260 230 360 730 600 306 390 420 291 710 340 217 281 352
[55] 259 250 470 680 570 350 300 560 900 625 332 2348 1171 3710 2315 2533 780 280
[73] 410 460 260 255 431 350 760 618 338 981 1306 500 696 605 250 411 1054 735
[91] 233 435 490 310 460 383 375 1270 545 445 1885 380 300 380 377 425 276 210
[109] 800 420 350 360 538 1100 1205 314 237 610 360 540 1038 424 310 300 444 301
[127] 268 620 215 652 900 525 246 360 529 500 720 270 430 671 1770
at first I tried these but didn't work:
> ggplot(rivers,aes(rivers))+geom_histogram()
Error: ggplot2 doesn't know how to deal with data of class numeric
> ggplot(rivers)+geom_histogram(aes(rivers))
Error: ggplot2 doesn't know how to deal with data of class numeric
then i found a similar question and figured out that i can achieve my goal by:
ggplot()+aes(rivers)+geom_histogram()
or
ggplot()+geom_histogram(aes(rivers))
i read through ggplot help documentation and have following questions:
ggplot(aes(rivers))+geom_histogram() Error: ggplot2 doesn't know how to deal with data of class uneval
Upvotes: 5
Views: 18251
Reputation: 1
You can also use qplot() which is a shortcut for producing plots quickly. It is a function of ggplot2. The following code will solve your problem:
qplot(rivers, geom="histogram")
Upvotes: -1
Reputation: 1956
If you don't provide argument name to ggplot
explicitly, then value is assigned to the wrong ggplot
argument (first in sequential order is data
arg). Arguments order can be seen on the relevant function help page:
?ggplot
ggplot(data = NULL, mapping = aes(), ..., environment = parent.frame())
Therefore when you provide aes()
to ggplot without specifying argument name, it's like if you do the following:
ggplot(data = aes(rivers)) + geom_histogram()
since data
argument don't allow this data type - you get an error.
providing correct argument name solves the problem:
ggplot(mapping = aes(rivers)) + geom_histogram()
Upvotes: 7
Reputation: 887158
The reason for the error is rivers
is a vector
.
ggplot(aes(rivers))+
geom_histogram()
Error: ggplot2 doesn't know how to deal with data of class uneval. Did you accidentally provide the results of
aes()
to thedata
argument?
Convert it to data.frame
and then it would work
library(ggplot2)
library(dplyr)
data_frame(val = rivers) %>%
ggplot(., aes(val)) +
geom_histogram()
set.seed(24)
rivers <- sample(700:1700, 150)
Upvotes: 5