ggplot2绘制多geom_smooth曲线及自定义颜色问题求助
问题解决方案
核心问题原因
你的year.x是数值型变量,ggplot默认将其视为连续变量处理:
- 导致
geom_smooth不会按年份分组拟合,仅生成一条整体趋势曲线; scale_color_manual仅对离散分类变量生效,因此无法修改颜色。
解决步骤
- 将
year.x转换为因子型变量,让ggplot识别为离散分组,这样每个年份会单独生成趋势线,颜色映射也能正常工作; - 由于
geom_smooth使用了fill=year.x,需同步添加scale_fill_manual匹配置信区间的填充色,避免颜色混乱。
修改后的代码
year_1999 <- subset(count_all, year.x <= 2004) # 将年份转换为因子,确保ggplot按离散分组处理 year_1999$year.x <- as.factor(year_1999$year.x) first.plot <- ggplot(year_1999, aes(temperature, ENS, col=year.x))+ geom_point(shape=17)+ geom_smooth(aes(fill=year.x))+ # 手动设置线条颜色,顺序对应年份因子的水平 scale_color_manual(values = c("green","darkorange","darkblue", "darkgrey", "yellow","red"))+ # 同步设置置信区间填充色,和线条颜色对应 scale_fill_manual(values = c("green","darkorange","darkblue", "darkgrey", "yellow","red"))+ ylab("ENS")+ xlab("Temperature [°C]")+ ggtitle("1999-2004")+ # 统一线条和填充的图例名称 labs(color = "Year", fill = "Year")+ theme(plot.title = element_text(hjust = 0.5))+ theme(axis.title.y=element_text(size=18,colour="black",vjust=0.7),axis.text.y=element_text(size=12,face="bold",colour="black",angle=0,hjust=0.9))+ theme(axis.title.x=element_text(size=18,colour="black",vjust=0.2),axis.text.x=element_text(size=12,colour="black",face="bold"))+ theme(panel.grid.major=element_blank(),panel.grid.minor=element_blank())+ theme(plot.margin=unit(c(0.2,0.2,.2,0.2),"cm"))+ theme(panel.border=element_rect(colour="black",size=1.5))+ theme(axis.ticks=element_line(colour="black",size=1),axis.ticks.length=unit(0.3,"cm")) first.plot
额外提示
如果转换因子后年份顺序不符合预期,可以手动指定因子水平:
year_1999$year.x <- factor(year_1999$year.x, levels = c(1999,2000,2001,2002,2003,2004))
这样能保证颜色和年份一一对应。
内容的提问来源于stack exchange,提问作者lxrnax
相关产品推荐
相关产品推荐

