使用带有facet的qplot时出错?

时间:2017-04-04 15:30:07

标签: r plot ggplot2 statistics

我正在尝试使用此数据进行直方图以获取使用ggplot2创建图形的示例,然后我发现我无法使用qplot命令使用facet进行此直方图,我已经使用其他数据执行此类绘图,但现在我再次尝试使用这些特定数据,我无法做到。

这是代码:

library(ggplot2)
qplot(x      = diamonds$price,
      geom   = "histogram",
      facets = .~diamonds$cut)

正如您所看到的,实际上非常简单,但它给了我错误:

  

错误:找不到'cut'的值

如果您进行快速研究,您会发现切割因子中每个级别都有价格值。

diamonds$price[diamonds$cut=="Fair"]
diamonds$price[diamonds$cut=="Good"]
diamonds$price[diamonds$cut=="Very Good"]
diamonds$price[diamonds$cut=="Premium"]
diamonds$price[diamonds$cut=="Ideal"]

我无法理解有什么不对。

这是另一个例子。但这很有效。

x <- rnorm(120,20,20)
y <- as.factor(c(rep("yo",60),rep("tu",60)))
df <- data.frame(x,y)
qplot(x = df$x, geom = "histogram", facets = .~df$y)

这些数据有什么不同?我看不到它。

这告诉我变量类在这两个例子中是相同的

is.numeric(diamonds$price)
  

[1] TRUE

is.numeric(x)
  

[1] TRUE

is.factor(diamonds$cut)
  

[1] TRUE

is.factor(y)
  

[1] TRUE

请帮忙。

1 个答案:

答案 0 :(得分:1)

以下答案基于aosmith帮助,谢谢。

问题是qplot实际上没有读取示例编号2中的df $ x和df $ y变量:

library(ggplot2)    
x <- rnorm(120,20,20)
y <- as.factor(c(rep("yo",60),rep("tu",60)))
df <- data.frame(x,y)
qplot(x = df$x, geom = "histogram", facets = .~df$y)

在这个例子中,qplot读取对象x和y,在前两行中创建,它从不使用df $ x或df $ y。

因此,在示例中,数字1:

qplot(x      = diamonds$price,
      geom   = "histogram",
      facets = .~diamonds$cut)

环境中没有价格或削减对象,这就是我收到错误的原因。

解决方案:使用参数data =

像这样:

qplot(data = diamonds,
      x = price,
      geom = "histogram",
      facets = .~cut)
相关问题