r - 使用 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)
不起作用,我认为应该这样做,因为变量是一个字符串......
解决方案
如果它只是关于标签名称,您可以使用 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)
}
推荐阅读
- node.js - 在 mongodb 中使用 node.js 搜索技术?
- angular - 寻找一种在 Angular 6 中绑定大量相同下拉列表的有效方法
- java - 只想填写二维数组的顶行和底行
- python - ImportError:“pytest”中没有名为请求的模块
- html - 为什么我的 flex wrap 实际上没有将我的物品堆叠在一起?
- java - 将 MediaRecorder .3gpp 转换为字节,然后检索回 .3gp 不起作用
- java - 杰克逊动态 Json 与 Class 自动映射
- python - 使用 for 循环创建等效的 np.meshgrid
- ios - 为什么即使我输入相同的 RGB 数字,颜色也会略有不同?
- c++ - While(!inputfile.eof()) 只读取第一行?