0
votes

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
1
How is this related to python? Also "none of these seem seem to work" is not a proper description of a programming issue.Stop harming Monica
You could do this by preprocessing the data to create your dynamic label then use ggplot.Jake Kaupp
Including reproducible data would make it substantially easier to help you stackoverflow.com/questions/5963269/…Mark Peterson
@JakeKaupp Thanks! Please check edited question and offer suggestion.Panzer M
Updated the question to make a lot more clear. Thanks guys!Panzer M

1 Answers

0
votes

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