r - 如何为折线图手动添加图例
问题描述
如何为 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)
解决方案
我认为最巧妙的方法是添加colour = "[label]"
到然后将手动分配颜色的aes()
部分添加到这里的示例中(抱歉,它使用而不是使用相同的技巧):geom_line()
scale_colour_manual()
mtcars
stat_summary
geom_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") +
...
(但我无法测试您的数据,所以不确定它是否有效)
推荐阅读
- node.js - 无法在节点 opc ua 服务器中导入自定义节点集
- ios - 如何使用 SwiftUI List 中的自定义视图平滑扩展行单元格?
- python - 使用python将图像的颜色更改为特定的调色板
- entity-framework-core-3.1 - EF Core 3.1.x:无法翻译 LINQ 表达式。以可以翻译的形式重写查询
- javascript - React 中的严格模式...为什么
重复运行代码两次? - php - SQLSTATE[HY000]:一般错误:1364 字段“banner_photo”没有默认值
- html - 如何通过动态标签系统显示不同的列表?
- time - Pine Script - 买入卖出信号来来去去
- reactjs - reactjs - 如何在地图中实现 onChange 处理程序?
- javascript - 如何选择自定义元素的子元素的位置?