简体   繁体   中英

Framework for adding lines on existing plots: "points" and "plot" in ggplot

This is probably a pretty naive question. I searched and couldn't find a duplicate, but please let me know if this has already been asked!

I have some functions that, based on a boolean argument, either make a new plot or plot ontop of the existing graph. Here's a MWE:

plotThing <- function(boolPoints = FALSE, color = "black") {
    x <- sample(c(1:100), size = 10, replace=TRUE)
    y <- sample(c(1:100), size = 10, replace=TRUE)

    if(boolPoints) {
            points(y~x, col = color, pch = 19)
    }

    else {
            plot(y~x, col = color, pch = 19)
    }
}

This style of function has been useful for me because I import all of these functions into a markdown document, and then it's really easy to just plot a arbitrarily large amount of points on one plot. For example, in the markdown document:

```{r MWE}
source("MWE.R")
plotThing();
plotThing(boolPoints = TRUE, color = "red")
legend("topright", title = "Things", c("thing1", "thing2"), pch = c(19,19), col = c("black", "red"))
```

In the actual code, I think this style might be a good choice because my plotting functions are pretty large and have lots of arguments that would be ugly to repeat over and over again.

Is it possible/how would I have an equivalent setup with ggplot? Or is this just poor design that you'd recommend changing?

I am not sure whether this will directly answer your question, but I think it might help.

So, in ggplot2 you have the nice feature of being able to save plots without printing them:

p <- ggplot(mtcars, aes(x=hp, y=mpg)) + geom_point()

Now, you could - based on a condition - add further points to the same plot if you have gathered more data and print it or just print the basic plot:

if(addPoints){
    print(p + geom_point(data = data.frame(hp=500, mpg=50)))
} else {
    print(p)
}

However, if you add additional data to the plot you would just have to make sure that the aesthetic mapping matches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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