Reputation: 103
I have a function in R that reads data off a website and plots 2 columns. How can I make it so that the first time I run the function it initializes a new graph, but then subsequent runs (which will be marked with a 'reset' parameter) will add a new set of points to the graph rather than overwriting the old one?
getdata<- function(team,year,reset=F){
#Retrieve/format Data
[..]
#Plot Data
if (reset==T)
{
p <-ggplot(data, aes(x = no, y = pts)) +
geom_path(colour="red", size=2) +
geom_point(colour="black" ,size = 2, shape=21, fill="white")
return(p)
}
else
{
add<-ggplot(data, aes(x = no, y = pts)) +
geom_path(colour = "blue", size = 2) +
geom_point(colour="black", size = 2, shape=21, fill="white")
p <- p + add
return(p)
}
I think my issue is similar to this posted here: Adding line with points to a plot in ggplot2 but I'm having some trouble adding the it as a list to the currently existing plot.
I'm a beginner with R so might be doing something stupid!
Thanks for any help, been wrestling with this for a while.
Upvotes: 1
Views: 927
Reputation: 52687
There are a few things that need to happen for this to work:
geom_point()
) to your plot, not an entire ggplot
objectSo here is a potential implementation (note, untested since your example is not reproducible):
make_getdata <- function() { # THIS FUNCTION RETURNS A FUNCTION
p <- NULL # WE WILL STORE PLOT HERE
function(team,year,reset=F) {
# get data
if(reset || is.null(p)) {
p <<- ggplot(data, aes(x = no, y = pts)) + # NOTICE DOUBLE ARROW
geom_path(colour="red", size=2) +
geom_point(colour="black" ,size = 2, shape=21, fill="white")
} else {
p <<- p + # NOTICE DOUBLE ARROW
geom_path(data=data, aes(x = no, y = pts), colour = "blue", size = 2) +
geom_point(data=data, aes(x = no, y = pts), colour="black", size = 2, shape=21, fill="white")
}
return(p)
} }
getdata <- make_getdata() # this creates your `getdata` function and stores it in `getdata`
getdata(...)
The key here is we take advantage of R's scoping properties to create a persistent variable were we store the graph. make_getdata()
creates a function as well as a function environment. That environment contains p
, which we can use to store our plots with <<-
.
Upvotes: 2