subset =。()不能直接在ggplot()中调用

时间:2015-05-25 09:41:15

标签: r ggplot2 subset

以下几行想要做的很清楚:

ggplot(data=mtcars, aes(x=mpg, y=cyl), subset=.(gear=="5")) + 
geom_point(aes(colour=gear))

但它不起作用(子集只是被忽略)。确实有效的是:

ggplot(data=mtcars, aes(x=mpg, y=cyl)) +
geom_point(aes(colour=gear), subset=.(gear=="5"))

或者:

ggplot(data=subset(mtcars, gear=="5"), aes(x=mpg, y=cyl)) +
geom_point(aes(colour=gear))

所以看起来子集只能从几何调用中调用,而不能直接从ggplot()调用。 这是一个错误还是这是正确的行为? ggplot不会返回任何类型的警告或错误。

1 个答案:

答案 0 :(得分:3)

I don't think this is a bug. It looks like it is intended if you see the source code of the two functions: ggplot and geom_point:

For ggplot:

> getAnywhere(ggplot.data.frame)
A single object matching ‘ggplot.data.frame’ was found
It was found in the following places
  registered S3 method for ggplot from namespace ggplot2
  namespace:ggplot2
with value

function (data, mapping = aes(), ..., environment = globalenv()) 
{
    if (!missing(mapping) && !inherits(mapping, "uneval")) 
        stop("Mapping should be created with aes or aes_string")
    p <- structure(list(data = data, layers = list(), scales = Scales$new(), 
        mapping = mapping, theme = list(), coordinates = coord_cartesian(), 
        facet = facet_null(), plot_env = environment), class = c("gg", 
        "ggplot"))
    p$labels <- make_labels(mapping)
    set_last_plot(p)
    p
}
<environment: namespace:ggplot2>

And geom_point:

> geom_point
function (mapping = NULL, data = NULL, stat = "identity", position = "identity", 
    na.rm = FALSE, ...) 
{
    GeomPoint$new(mapping = mapping, data = data, stat = stat, 
        position = position, na.rm = na.rm, ...)
}
<environment: namespace:ggplot2>

If you look at the ellipsis argument ... you will see that it is not used in the ggplot function. So, your use of the argument subset=.() is not transferred or used anywhere. It does not give any errors or warnings however because of the existence of the ellipsis in the ggplot function.

On the other hand the geom_point function uses the ellipsis and transfers it to GeomPoint$new where it is used. In this case your subset=.() argument is transferred to GeomPoint$new where it is used, producing the result you want.

相关问题