如何使用字符向量设置ggplot2的fill美学映射?
解决ggplot中用字符向量指定fill美学映射的问题
问题原因
直接在aes(fill=ClusterElement)中传入字符串变量时,ggplot会将其视为离散的常量值(整个图表的fill都被设为"Fe"这个字符串),但你使用的scale_fill_distiller是针对连续型数据的色阶,两者类型不匹配,因此触发报错。
正确解决方案
使用ggplot的.data pronoun按列名引用数据框中的连续型列,这是当前官方推荐的方法:
ClusterElement <- "Fe" ggplot(df) + geom_col(aes(x = factor(Cluster), y = 1, fill = .data[[ClusterElement]])) + scale_fill_distiller(palette = "RdBu", direction = 1) + labs(fill = ClusterElement) # 无需paste0,直接调用变量即可
兼容旧版ggplot的替代方法
如果使用的是较旧版本的ggplot2,也可以用aes_string函数直接传入字符串形式的映射参数:
ClusterElement <- "Fe" ggplot(df) + geom_col(aes_string(x = "factor(Cluster)", y = "1", fill = ClusterElement)) + scale_fill_distiller(palette = "RdBu", direction = 1) + labs(fill = ClusterElement)
之前尝试无效的原因
fill=colnames() %in% ClusterElement:返回的是逻辑向量(TRUE/FALSE),属于离散型数据,和连续色阶不匹配。fill=matches(ClusterElement):matches()是dplyr中用于列选择的函数,无法直接在aes()内部使用,不能正确映射目标数据列。
内容的提问来源于stack exchange,提问作者JJGabe
相关产品推荐
相关产品推荐

