ggplot2折线图与饼图图例顺序及颜色统一调整需求
解决方案
1. 饼图百分比保留1位小数
直接修改饼图代码中geom_text的round函数参数,指定保留1位小数即可:
geom_text(aes(label = paste0(round(Percentage, 1), "%")), position = position_stack(vjust = 0.5))
2. 统一折线图与饼图的图例顺序及颜色
核心是统一两个数据集的因子水平,并通过手动颜色映射固定组件颜色,具体实现如下:
第一步:定义全局统一配置
先提前设定好固定的组件顺序和对应颜色,避免重复编写配置:
# 指定统一的组件显示顺序 component_order <- c("Stem", "Bark", "Needle", "Branch", "Cone") # 定义组件对应的颜色映射 component_color_map <- c( Stem = "Coral1", Bark = "Brown1", Needle = "chartreuse", Branch = "Cornsilk3", Cone = "darkgreen" )
第二步:修改折线图代码
将数据集的Component字段转为指定顺序的因子,并通过scale_color_manual绑定颜色:
# 转换因子水平,强制组件顺序 DRProportions$Component <- factor(DRProportions$Component, levels = component_order) # 生成折线图 plotly::ggplotly( ggplot(DRProportions, aes(x = DBH, y = Percentage, color = Component)) + labs(y = "Percentage (%)", x = "DBH (cm)") + geom_line(lwd = 1.1) + geom_point(size = 2.5) + scale_color_manual(values = component_color_map) # 绑定统一颜色 )
第三步:修改饼图代码
同样转换Component的因子水平,并用scale_fill_manual绑定颜色,同时应用小数保留的修改:
# 转换因子水平,强制组件顺序 DR_Model$Component <- factor(DR_Model$Component, levels = component_order) # 生成饼图 ggplot(DR_Model, aes(x = "", y = Percentage, fill = Component)) + geom_bar(width = 1, size = 1, color = "white", stat = "identity") + geom_text(aes(label = paste0(round(Percentage, 1), "%")), position = position_stack(vjust = 0.5)) + coord_polar(theta = "y") + theme_void() + scale_fill_manual(values = component_color_map) # 绑定统一颜色
逻辑说明
- 将
Component转为指定顺序的因子,可强制ggplot按照设定顺序生成图例,彻底避免默认的字母排序。 - 使用
scale_color_manual(折线图)和scale_fill_manual(饼图)绑定同一套颜色映射,确保两个图的组件颜色完全匹配。
内容的提问来源于stack exchange,提问作者Otto_P
相关产品推荐
相关产品推荐

