R ggplot:按索引指定 aes

发布于 2024-09-17 10:58:51 字数 412 浏览 2 评论 0原文

ggplot() +
layer(
 data = diamonds, mapping = aes(x = carat, y = price),
 geom = "point", stat = "identity"
)

在上面的示例中,我想知道是否可以通过索引指定“aes”函数的参数。

我知道克拉和价格对应于钻石名称数组中的第 1 个和第 8 个元素。您能解释一下为什么以下不起作用吗?

ggplot() +
layer(
 data = diamonds, mapping = aes(x = names(diamonds)[1], y = names(diamonds)[8]),
 geom = "point", stat = "identity"
)

谢谢,德里克

ggplot() +
layer(
 data = diamonds, mapping = aes(x = carat, y = price),
 geom = "point", stat = "identity"
)

In the above example, I am wondering if I can specify the parameters for the "aes" function by indexes.

I know that carat and price correspond to the 1st and 8th elements in the names array of diamond. Can you explain why the following does not work?

ggplot() +
layer(
 data = diamonds, mapping = aes(x = names(diamonds)[1], y = names(diamonds)[8]),
 geom = "point", stat = "identity"
)

Thanks, Derek

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

余厌 2024-09-24 10:58:51

第二个版本不起作用,因为 names(diamonds)[1]"carat" 而不是 carat。使用 aes_string 而不是 aes 来实现此目的。

ggplot( data = diamonds, mapping = aes_string(x = names(diamonds)[1], y = names(diamonds)[8]), stat = "identity")+ geom_point()

编辑:
要处理包含非法字符的名称,您必须将它们括在反引号中(任何时候您想使用它们时都是如此):

dd <- data.frame(1:10, rnorm(1:10))
names(dd) <- c("(PDH-TSV 4.0)(ET)(240)", "Y")
nms <- paste("`", names(dd), "`", sep="")
ggplot(dd, mapping=aes_string(x=nms[1], y=nms[2])) + geom_point()

The second version does not work because names(diamonds)[1] is "carat" and not carat. Use aes_string instead of aes for this to work.

ggplot( data = diamonds, mapping = aes_string(x = names(diamonds)[1], y = names(diamonds)[8]), stat = "identity")+ geom_point()

EDIT:
To deal with names that have illegal characters, you have to do enclose them in backticks (that's the case any time you want to use them):

dd <- data.frame(1:10, rnorm(1:10))
names(dd) <- c("(PDH-TSV 4.0)(ET)(240)", "Y")
nms <- paste("`", names(dd), "`", sep="")
ggplot(dd, mapping=aes_string(x=nms[1], y=nms[2])) + geom_point()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文