I created a lattice scatterplot using xyplot that is grouped into separate categories. Now I am trying to create a single hexplot for each of the categories from the scatterplot. I can hard code the variables but I would prefer to do it in a loop since I would be doing this multiple times which will have new categories.
I started with a table that looks like this
Name Category Value1 Value2
sample1 cat1 10 1.5
sample2 cat2 10 1.5
sample3 cat3 10 1.5
sample4 cat1 10 1.5
sample5 cat1 10 1.5
sample6 cat2 10 1.5
sample7 cat3 10 1.5
I was able to create a list of dataframes using
testing <- split(Mydata, Mydata$Category)
then I can create a plot by
testing2 <- as.data.frame(testing[["cat1"]]) #I keep on needing to change this for each Category that I have
ggplot(testing2, aes(x = testing2[,3], y = testing2[,4])) +
geom_hex(bins = 30)
testing2 looks like this
Name Category Value1 Value2
sample1 cat1 10 1.5
sample4 cat1 10 1.5
sample5 cat1 10 1.5
I tried
for(i in testing){
testing3 <- i
xtra <- ggplot(testing3, aes(x = testing3[,3], y = testing3[,4])) + geom_hex(bins = 30)
xtra
}
This ends up with xtra being the last dataframe on the list.
Can someone help me with this? I would want to be able to create plots without having to change $Category each time as I have >50 categories for everytime that I want to do this.
--edit1 As per suggestion, I created a function;
myFirstFun <- function(column)
{
testing2 <- as.data.frame(testing[[column]])
column <- enquo(column)
ggplot(testing2, aes_string(x ="Value1", y = "Value2", group = column)) +
geom_hex(bins = 30)
}
And this;
myFirstFun("cat1")
produces this;
Name Category Value1 Value2
sample1 cat1 10 1.5
sample4 cat1 10 1.5
sample5 cat1 10 1.5
but when I try to use a for loop;
for(i in categorynames){###categorynames is a vector that has all my categorynames
myFirstFun(i)
}
it will only produce the last graph on the list. How would I do this to produce n number of graphs (n = number of my categories)? Without me manually doing
myFirstFun("cat1")
myFirstFun("cat2")
myFirstFun("cat3")
...