R语言ggplot2图例排序失效,如何自定义顺序、移图例到图内并删标题?
问题根源
你的映射属性和调整的scale不匹配:你在aes()中使用color = treatment映射线条颜色,但添加的是针对填充属性的scale_fill_discrete,二者完全不对应,因此设置不会生效。
解决方法
1. 调整图例顺序
有两种常用方案,更推荐第一种从数据层面统一顺序,后续所有绘图都会默认使用该顺序:
- 方案1:转换treatment为因子时直接指定你需要的level顺序
treatment = factor(treatment, levels = c("C","3","4","5","10","HT"))
- 方案2:使用对应color属性的scale设置断点
scale_color_discrete(breaks = c("C","3","4","5","10","HT"))
2. 移动图例到绘图区域内部
在theme()中添加legend.position参数,参数值为长度为2的向量,数值范围0-1,对应画布的相对坐标:
- 左下角对应
c(0,0),右上角对应c(1,1),比如放在右上角内部可以写legend.position = c(0.9, 0.9),同时搭配legend.justification = c("right", "top")让图例右上角对齐你指定的坐标点,避免超出画布范围。
3. 删除图例标题
有两种实现方式:
- 在对应的scale中设置
name = NULL - 在
theme()中添加legend.title = element_blank()
完整可运行代码
library(tidyverse) df <- data.frame(treatment= c("C", "3", "4", "5", "10","HT"), day1 = c(0.23, 0.16, 0.34, 0.21, 0.17,0.34), day2=c(0.18,0.13,0.27,0.17,0.11,0.23), day4=c(0.15,0.08,0.20,0.14,0.05,0.17)) df %>% pivot_longer(-treatment, names_to = "days", names_prefix = "day") %>% mutate(days = as.integer(days), # 转换因子时直接指定顺序,一劳永逸 treatment = factor(treatment, levels = c("C","3","4","5","10","HT"))) %>% ggplot(aes(days, value, color = treatment)) + geom_line()+ ylab(expression(Transpiration (g/h)))+ xlab(expression(Days))+ theme_dark()+ theme( text = element_text(size = 20), # 图例放在右上角内部,可自行调整坐标数值适配需求 legend.position = c(0.95, 0.95), legend.justification = c("right", "top"), # 删除图例标题 legend.title = element_blank() )
内容的提问来源于stack exchange,提问作者Gonzalo de Quesada
相关产品推荐
相关产品推荐

