0

Here's my initial dataframe.

data.df

x y z label
2 3 4   1
1 2 3   2
2 4 3   3

To make ggplot, this works when there is only 1 column (label) :

    g <- ggplot(data.df) + 
       geom_point(data = data.df, aes(x= x, y= y, 
       color = ifelse(( label == 2), "a", "b")+
       scale_colour_manual(values= c("a" = "blue", "b" = "green"))

    return g 

On clicking a button called "merge", new column gets added dynamically:

x y z label label2
2 3 4   1     1
1 2 3   2     2
2 4 3   3     2

Now in ggplot I need to access LAST column instead of label column (it could be label2, label3...) and update ggplot.

I tried two ways.

  g <- ggplot(data.df) + 
       geom_point(data = data.df, aes(x= x, y= y, 
       color = ifelse(( data.df[, ncol(data.df)] == 2, "a", "b")+
       scale_colour_manual(values= c("a" = "blue", "b" = "green"))


  return g 

As shown while using data.df[, ncol(data.df)] , I'm getting the error:

Error: Aesthetics must be either length 1 or the same as the data (40): x, y, colour

I have a feeling aes_string can be used instead of aes:

 label <- paste("label", counter , sep="")

 g <- ggplot(data.df) + 
       geom_point(data = data.df, aes_string(x= "x", y= "y", 
       color = ifelse((label == 2), a, b))) +
       scale_colour_manual(values= c("a" = "blue", "b" = "green"))

I'm getting this error:

Error in ifelse((label == 2), a, b))),  : object a not found
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Panzer M
  • 55
  • 1
  • 8

1 Answers1

0

My opinion is to do your standard evaluation that allows for the dynamic functionality before you go into ggplot2 functions.

The below takes advantage of Standard evaluation versions of dplyr functions. It creates a column in the data frame dynamically called formatCol and bases the colour scale on it.

data.df <- data.frame(x = c(2, 1, 2),
                      y = c(3, 2, 4),
                      z = c(4, 3, 3),
                      label = c(1, 2, 3),
                      label2 = c(1, 2, 2))

library(ggplot2)
library(dplyr)
library(lazyeval)

formatCol <- names(data.df)[ncol(data.df)]
formula <- interp(~ifelse((label == 2), "a", "b"), label = as.name(formatCol))

plot.df <- data.df %>% mutate_(formatCol = formula)

  g <- ggplot(plot.df, aes(x= x, y= y)) + 
      geom_point( aes(color = formatCol))+
        scale_colour_manual(values= c("a" = "blue", "b" = "green"))

g
DataJack
  • 341
  • 2
  • 13
  • I found my error was with scale_colour_manual when testing out this code. This helped me make my code cleaner. Thank you! – Panzer M Dec 22 '16 at 12:57