使用功能将多层添加到ggplot [英] adding multiple layers to a ggplot with a function

查看:1426
本文介绍了使用功能将多层添加到ggplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将多个图形元素添加到现有的ggplot中.新元素将放置在指定的x值周围.简化后,我有一个原点为1的现有图p:

I am trying to add multiple graphical elements to an existing ggplot. The new elements will be placed around a specified x-value. Simplified, I have the existing plot p with one point at the origin:

library(ggplot2)
p <- ggplot(data = data.frame(x = 0, y = 0), aes(x = x, y = y)) +
  geom_point()

现在,我想创建一个可以基于定义的x位置向左和向右添加点的函数.我试过了:

Now I want to make a function that can add a point left and right, based on a defined x-position. I tried:

add_points <- function(x) {
  geom_point(aes(x = x - 1, y = 0), color = "red") +
  geom_point(aes(x = x + 1, y = 0), color = "red")
}

但是当我尝试使用添加它们时

But when I try to add them using

p + add_points(x = 0)

我知道

错误:无法将ggproto对象一起添加.您忘记添加了吗 对象到ggplot对象?

Error: Cannot add ggproto objects together. Did you forget to add this object to a ggplot object?

基于带有参数的函数添加多层的ggplot方法是什么?

What is the ggplot way of adding multiple layers based on a function that takes an argument?

PS:仅使用此功能添加一层是有效的,因此首先创建带有x值的小标题并将其馈送到geom_point也是可行的.但是实际上,我要向绘图中添加几个不同的几何图形,因此我认为我需要在函数中一起添加多个图层.

PS: only adding one layer using this function does work, so first creating a tibble with the x-values and feeding that to the geom_point instead also works. In reality however, I am adding several different geoms to the plot, so I think I need to add several layers together in the function.

推荐答案

来自help("+.gg"):

您还可以提供一个列表,在这种情况下,列表中的每个元素都会依次添加.

You can also supply a list, in which case each element of the list will be added in turn.

add_points <- function(x) {
  list(geom_point(aes(x = x - 1, y = 0), color = "red"),
    geom_point(aes(x = x + 1, y = 0), color = "red"))
}

p + add_points(x = 0)
#works

这篇关于使用功能将多层添加到ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆