使用ggplot2在R中从向量绘制直方图

4
我想用ggplot2从向量绘制直方图。数据集来自datasets包中的rivers。
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

一开始我尝试了这些方法,但是都没有起作用:

> 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

后来我发现了一个类似的问题,然后我找到了解决办法:

ggplot()+aes(rivers)+geom_histogram()
or
ggplot()+geom_histogram(aes(rivers))

我阅读了 ggplot 的帮助文档,有以下问题:
  • why i got error when i claim dataset in either ggplot() or geom_histogram(),like ggplot(data=rivers)? Help docs indicates a vector will be coerced to a data frame by default and a dataset must be specified. My assumption is that when a dataset is not specified, the function will search for global environment?
  • why it works when i call aes(rivers) independently or in geom_histogram() but i got error when i put it in gglot(). why the location of aes(rivers) matters in this case?
    ggplot(aes(rivers))+geom_histogram()
    Error: ggplot2 doesn't know how to deal with data of class uneval
    

1
看起来你有一个vector。将其转换为data.frame,然后使用ggplot - akrun
3个回答

6

如果您没有明确提供参数名称给 ggplot,那么该值将被错误地分配给 ggplot 参数(按顺序排列的第一个参数是 data)。相关函数帮助页面上可以看到参数的顺序:

?ggplot 

ggplot(data = NULL, mapping = aes(), ..., environment = parent.frame())

因此,当您在没有指定参数名称的情况下向ggplot提供时,就好像执行以下操作:

ggplot(data = aes(rivers)) + geom_histogram()

由于"data"参数不允许此数据类型 - 您会收到错误提示。 提供正确的参数名称即可解决问题:
ggplot(mapping = aes(rivers)) + geom_histogram()

5
错误的原因是 rivers 是一个向量
ggplot(aes(rivers))+
               geom_histogram()

错误: ggplot2不知道如何处理类别为uneval的数据。你是否不小心将的结果提供给data参数?

将其转换为data.frame,然后它将正常工作。

library(ggplot2)
library(dplyr)
data_frame(val = rivers) %>%
          ggplot(., aes(val)) + 
                geom_histogram()

数据

set.seed(24)
rivers <- sample(700:1700, 150)

{btsdaf} - Yin
{btsdaf} - akrun
{btsdaf} - Yin
{btsdaf} - akrun
{btsdaf} - Axeman

0
你也可以使用qplot(),它是快速生成图形的快捷方式。它是ggplot2的一个函数。以下代码将解决你的问题:
qplot(rivers, geom="histogram") 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接