简体   繁体   English

何时对 R 的 ggplot2 package 中的 geom_segment() function 的 xend 参数使用 aes 映射?

[英]When to use aes mapping for the xend argument of the geom_segment() function in R's ggplot2 package?

I'm trying to create 32 vertical line segments using the mpg column of the mtcars data frame.我正在尝试使用mtcars数据框的mpg列创建 32 个垂直线段。 All is good when I run the following code:当我运行以下代码时,一切都很好:

a <- ggplot (mtcars) 
b <- geom_segment (x = 1:32, y = 0, aes (xend = 1:32, yend = mpg))
a + b

在此处输入图像描述

However, when I define the xend argument outside the aes() function, it looks like this.但是,当我在aes() function 之外定义xend参数时,它看起来像这样。

a <- ggplot (mtcars) 
b <- geom_segment (x = 1:32, y = 0, xend = 1:32, aes (yend = mpg))
a + b

在此处输入图像描述

My question is, why doesn't it work?我的问题是,为什么它不起作用? Why can I define x and y outside the aes() function but not xend ?为什么我可以在aes() function 之外定义xy而不是xend What does the new chart mean?新图表是什么意思?

So, to briefly recap, the purpose of the aes() function is to link up aesthetics with scales so they can be mapped.因此,简要回顾一下, aes() function 的目的是将美学与比例联系起来,以便可以映射它们。 This is also why colour = "blue" will give a blue colour outside aes() but gets mapped to a discrete colourscale if you put it inside aes() .这也是为什么colour = "blue"会在aes()之外给出蓝色,但如果你把它放在aes()里面,它会被映射到一个离散的色阶。

Scales, amongst other things, measure the limits of the data range.除其他外,天平测量数据范围的限制。 If you define both x and xend outside the aes() and therefore these are not directly linked to a scale, the measurement that the scales are going to make won't see these values.如果您在aes()之外同时定义xxend ,因此它们不直接链接到刻度,则刻度将进行的测量将看不到这些值。

You can see in the example below that using that strategy gives you an x-scale that has default limits, instead of the limits as you would measure from the data.您可以在下面的示例中看到,使用该策略为您提供了一个具有默认限制的 x 比例,而不是您从数据中测量的限制。

library(ggplot2)

a <- ggplot (mtcars) 
b <- geom_segment (x = 1:32, y = 0, xend = 1:32, aes (yend = mpg))
g <- a + b

sc <- layer_scales(g)
(sc$x$get_limits())
#> [1] 0 1

Created on 2020-12-10 by the reprex package (v0.3.0)reprex package (v0.3.0) 于 2020 年 12 月 10 日创建

If you play around a bit more, you can see that you can define geom_segment (aes(x = 1:32, yend =mpg), y = 0, xend = 1:32) , which doesn't link the xend to a scale, but will display correctly anyway due to the scale seeing the x mapping.如果您玩得更多,您会看到您可以定义geom_segment (aes(x = 1:32, yend =mpg), y = 0, xend = 1:32) ,它不会将xend链接到比例,但由于看到x映射的比例,无论如何都会正确显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM