ggplot2修改图例标题时出现重复图例问题求助
解决ggplot2设置图例标题后出现两个图例的问题
问题原因
你同时在aes()里把member_type映射给了fill(填充色)和color(边框色)两个属性。一开始ggplot会因为两个属性映射的是同一个变量,自动合并图例;但当你只在labs()里修改fill的标题时,两个图例的标题不一致,ggplot就会把它们拆成两个独立的图例。
两种解决方案
方案1:同时设置fill和color的标题,让它们一致
在labs()里同时指定fill和color的标题为同一个内容,ggplot就会自动合并图例:
data_2023_2 %>% group_by(rideable_type, member_type) %>% dplyr::summarize(total_trips = n()) %>% ggplot(aes(x=rideable_type, y=total_trips, fill=member_type, color=member_type)) + geom_bar(stat='identity', position = position_dodge2(preserve = "single", padding = 0.1)) + geom_text(aes(label = total_trips), position = position_dodge2(preserve = "single", width = 0.9, padding = 0.1), vjust=1.5, colour="white") + scale_fill_manual(values=c("darkorchid","darkseagreen")) + scale_color_manual(values=c("darkorchid","darkseagreen")) + theme_bw()+ labs(title="Number of Trips by Bike Type", x="Bicycle Type", y="Number of Rides", fill="Member Type", color="Member Type")
方案2:直接隐藏color的图例(更简洁)
因为你设置的填充色和边框色完全一样,其实不需要保留color的图例,用guides()函数把它隐藏即可:
data_2023_2 %>% group_by(rideable_type, member_type) %>% dplyr::summarize(total_trips = n()) %>% ggplot(aes(x=rideable_type, y=total_trips, fill=member_type, color=member_type)) + geom_bar(stat='identity', position = position_dodge2(preserve = "single", padding = 0.1)) + geom_text(aes(label = total_trips), position = position_dodge2(preserve = "single", width = 0.9, padding = 0.1), vjust=1.5, colour="white") + scale_fill_manual(values=c("darkorchid","darkseagreen")) + scale_color_manual(values=c("darkorchid","darkseagreen")) + theme_bw()+ labs(title="Number of Trips by Bike Type", x="Bicycle Type", y="Number of Rides", fill="Member Type") + guides(color = "none") # 隐藏color对应的图例
内容的提问来源于stack exchange,提问作者aoao
相关产品推荐
相关产品推荐

