1

I have a list of dataframes and am making column plots for each using ggplot. I can make the plots, but am having trouble adding axis labels.

Here is the code I have so far (which works):

library("ggplot2")

zz.dat <- structure(list(exp.mean = c(5.1, 4.9, 4.7, 4.6, 5, 5.4), se = c(0.2, 
  0.2, 0.2, 0.2, 0.2, 0.4), species = structure(c(1L, 1L, 1L, 2L, 
  2L, 2L), .Label = c("a", "b"), class = "factor"), target = structure(c(1L, 
  2L, 3L, 1L, 2L, 3L), .Label = c("gg", "hh", "ii"), class = "factor")), 
                    class = "data.frame", row.names = c("1", 
                                                        "2", "3", "4", "5", "6"))

zz.plot <- split(zz.dat, zz.dat$target)
p <- lapply(zz.plot,
            function(d) ggplot(data=d, aes(x=species, y=exp.mean, color=species, fill=species)) +
              geom_col() +
              geom_errorbar(aes(ymin = exp.mean-se, ymax = exp.mean+se), width=0.2))

The plots then have labels of exp.mean and species. I tried to add a y-axis label in the lapply ggplot function:

p <- lapply(zz.plot, 
             function(d) ggplot(data=d, aes(x=species, y=exp.mean, color=species, fill=species)) +
               geom_col() +
               geom_errorbar(aes(ymin = exp.mean-se, ymax = exp.mean+se), width=0.2)) +
               ylab("Relative Gene Expression")

which gave the error

Error in lapply(qpcr_plot, function(d) ggplot(data = d, aes(x = Sample.Name,  : 
  non-numeric argument to binary operator

I then tried using a for loop to individually add a y label to each plot:

for(i in 1:length(p)){
  r[i] <- p[i] + ylab("Relative Gene Expression")
  print(r[i])
}

which gave me the same error.

melo37
  • 11
  • 2
  • 1
    If looks like you have your closing parenthesis for the `lapply` before the `ylab()` rather than after so it's not part of the function you create. This looks like just a typo / syntax error. The `for` loop gives the error because you should be extracting elements from a list with `p[[i]]` not `p[i]`. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. Since we can't run the code we are just guessing. – MrFlick Jun 11 '19 at 21:06
  • Thanks, that was it! Updated the question to be reproducible. :) – melo37 Jun 12 '19 at 02:24

0 Answers0