使用 get 时更改 R 图例标签

Changing R legend label when using get

假设你有数据:

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

我编写了一个以列名作为参数的函数:

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)
}

因此您可以运行这样做:plotFill(df,"C")

我试图用传递的变量的名称来标记图例,但是添加 labs(colour=variable) 不起作用,我认为应该这样做,因为变量是一个字符串...

如果只是关于标签名称,您可以使用 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)
}

你不应该在这里使用 get。相反,使用 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")