My idea is to create a set of functions (ggplot2) that are some kind of hierarchically structured to create and edit a plot. So there will be a function that defines the grid first, another functions plots the data and several other functions add optional data/lines/polygons.
Here’s a small working example that should clarify my concern:
# a first function that creates the grid and background and
# manipulates some data
plot.func <- function() {
a <<- 1
b <<- c(1,2,3,4)
z <<- 0:15
gg <<- ggplot(data=data, aes(x=height, y=weight)) +
geom_point()
return(gg)
}
# functions that add something to the plot working with
# objects defined in another functions
add.vline <- function(height) {
d <<- a+b
gg <<- gg + geom_vline(xintercept=height)
return(gg)
}
add.hline <- function(weight) {
e <<- z-d
gg <<- gg + geom_hline(yintercept=weight)
return(gg)
}
plot.func()
add.vline(60)
add.hline(154)
As your see I (have to?) work with <<-
a lot, because each functions only operates in his own (temporary?) environment. And to share the objects each functions has to have access to, I use <<-
to make these objects available globally.
I'm quite sure, that there's a right (and nicer) way to do that. Maybe or even probably my approach is totally wrong but I did not find another solution.
UPDATE: Here's an example how I would like to use parameters like style
to influence the following functions:
plot.func <- function(style) {
style <<- style
gg <- ggplot(data=data, aes(x=height, y=weight)) +
geom_point()
return(gg)
}
add.vline <- function(style, height) {
if (style == 0) {
gg <- gg + geom_vline(xintercept=height, col=red)
} else {
gg <- gg + geom_vline(xintercept=height, col=red)
}
return(gg)
}
gg <- plot.func(0)
add.vline(gg, 65)