Roey Angel
unread,Nov 7, 2012, 8:12:56 PM11/7/12Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to ggp...@googlegroups.com
Hi,
I'm trying to generate some ggplot functions but give the user the option of choosing which variables to plot by parsing their names (data frame column names).
Seems like a basic option to me to enable function writing but so far I've been unsuccessful -- ggplot either gives an error or otherwise funny results.
For example, given the following minimal data frame:
library(ggplot2)
data2plot <- data.frame(x1 = seq(1,10), y1 = seq(1,10), y2 = seq(10,1))
Now I'd like to generate a ggplot function that will plot a simple scatter plot but will accept column names as input so that the user could choose by name which column to plot.
but...
Running this:
plot.variable <- function(data2plot, y.axis){
qplot(x1, y = y.axis, data = data2plot)
}
plot.variable(data2plot, y.axis = 'y1')
Plots ten points on the graph with the Y value = 'y1'
Running this:
plot.variable <- function(data2plot, x.axis, y.axis){
qplot(x = x.axis, y = y.axis, data = data2plot)
}
plot.variable(data2plot, x.axis = 'x1', y.axis = 'y1')
Plots one point 'x1' vs 'y1'
Running this:
plot.variable <- function(data2plot, x.axis, y.axis){
qplot(data = data2plot, x = data2plot[, x.axis], y = data2plot[, y.axis])
}
plot.variable(data2plot, x.axis = 'x1', y.axis = 'y1')
Actually gives a plot but if I write a function using 'ggplot' instead of qplot:
plot.variable <- function(data2plot, x.axis, y.axis){
ggplot(data2plot, aes(x = data2plot[, x.axis], y = data2plot[, y.axis])) +
geom_point()
}
plot.variable(data2plot, x.axis = 'x1', y.axis = 'y1')
Gives and error: 'Error in `[.data.frame`(data2plot, , x.axis) : object 'x.axis' not found'
I could get this function to not give an error if I assign the variables outside the function call (i.e. x.axis <- 'x1', y.axis <- 'y1'), but that causes a mess with more complex functions which include faceting etc. I guess because it doesnt keep the original order of observations as in the data frame. Besides that's obviosly not a solution to my problem.
Is there a solution to this?
Thanks in advance,
Roey