首页 > 解决方案 > 如何为折线图手动添加图例

问题描述

我需要计划图例

如何为 geom_line 手动添加图例

ggplot(data = impact_end_Current_yr_m_actual, aes(x = month, y = gender_value)) + 
    geom_col(aes(fill = gender))+theme_classic()+
    geom_line(data = impact_end_Current_yr_m_plan, aes(x=month, y= gender_value, group=1),color="#288D55",size=1.2)+
    geom_point(data = impact_end_Current_yr_m_plan, aes(x=month, y=gender_value))+
    theme(axis.line.y = element_blank(),axis.ticks = element_blank(),legend.position = "bottom", axis.text.x = element_text(face = "bold", color = "black", size = 10, angle = 0, hjust = 1))+
    labs(x="", y="End Beneficiaries (in Num)", fill="")+
    scale_fill_manual(values=c("#284a8d", "#00B5CE","#0590eb","#2746c2"))+
    scale_y_continuous(labels = function(x) format(x, scientific = FALSE)

标签: rggplot2

解决方案


我认为最巧妙的方法是添加colour = "[label]"到然后将手动分配颜色的aes()部分添加到这里的示例中(抱歉,它使用而不是使用相同的技巧):geom_line()scale_colour_manual()mtcarsstat_summarygeom_line

library(tidyverse)

mtcars %>% 
  ggplot(aes(gear, mpg, fill = factor(cyl))) +
  stat_summary(geom = "bar", fun = mean, position = "dodge") +
  stat_summary(geom = "line", 
               fun = mean, 
               size  = 3, 
               aes(colour = "Overall mean", group = 1)) +
  scale_fill_discrete("") +
  scale_colour_manual("", values = "black")

reprex 包于 2020-12-08 创建(v0.3.0)

这里的限制是颜色和填充图例必须是分开的。删除标签(两个调用中的空白标题scale_)不会按图例标题将它们分开。

在您的代码中,您可能想要:

...
ggplot(data = impact_end_Current_yr_m_actual, aes(x = month, y = gender_value)) + 
    geom_col(aes(fill = gender))+
    geom_line(data = impact_end_Current_yr_m_plan, 
              aes(x=month, y= gender_value, group=1, color="Plan"), 
              size=1.2)+
    scale_color_manual(values = "#288D55") +
...

(但我无法测试您的数据,所以不确定它是否有效)


推荐阅读