首页 > 解决方案 > 使用 get 时更改 R 图例标签

问题描述

假设您有数据:

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)不起作用,我认为应该这样做,因为变量是一个字符串......

标签: rggplot2legend

解决方案


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


推荐阅读