Joezerz
Joezerz

Reputation: 151

Changing R legend label when using get

Suppose you have data:

df = data.frame(A = rep(1:10,each=10),B = rep(1:10,times=10),C = runif(100,0,1))

I've written a function that takes a column name as an argument:

plotFill<-function(dataframe,variable){
  if(!(variable %in% names(dataframe))) stop("Variable not in data.frame")
  plot = ggplot(data=dataframe,aes(x=A,y=B,z=get(variable))) + 
     geom_tile(aes(fill=get(variable)))
  return(plot)
}

You can therefore run this doing: plotFill(df,"C")

I'm trying to label the legend with the name of the variable passed, but adding labs(colour=variable) doesn't work, which I think it should since variable is a string...

Upvotes: 0

Views: 85

Answers (2)

Roland
Roland

Reputation: 132959

You shouldn't use get here. Instead, use aes_string.

plotFill<-function(dataframe,variable){
  if(!(variable %in% names(dataframe))) stop("Variable not in data.frame")
  plot = ggplot(data=dataframe,aes_string(x="A",y="B",z=variable)) + 
    geom_tile(aes_string(fill=variable))
  return(plot)
}

plotFill(df,"C")

Upvotes: 1

maarvd
maarvd

Reputation: 1284

If its only about the label name, you could use plot$labels$fill:

plotFill<-function(dataframe,variable){
  if(!(variable %in% names(dataframe))) stop("Variable not in data.frame")
  plot = ggplot(data=dataframe,aes(x=A,y=B,z=get(variable))) + 
    geom_tile(aes(fill=get(variable)))

  plot$labels$fill <- variable

  return(plot)
}

Upvotes: 1

Related Questions