如何为ggplot2的facet_wrap绘图添加统一彩色线型主图例
为ggplot2的facet_wrap添加统一主图例的方法
要给facet_wrap的图表添加统一的主图例,核心是把线条的颜色、线型映射到ggplot的美学属性(aes)中,而非直接在geom层固定参数。以下是修改后的可复现代码和关键步骤说明:
修改后的完整代码
library(quantmod) library(purrr) library(tidyverse) library(stats) start_date <- as.Date("2018-02-02") end_date <- as.Date("2018-09-24") adjustment <- TRUE symbol <- c("AAPL", "AMZN", "MSFT") getSymbols(symbol, src = "yahoo", from = start_date, to=end_date, adjust = adjustment) DFCONVERT<- function (sym) { library(xts) newdata<-list() newdata[[sym]]<-data.frame(Date=index(eval(as.symbol(sym))), coredata(eval(as.symbol(sym)))) columnnames<- c("Date", "Open", "High", "Low", "Close", "Volume", "Adjusted") newdata[[sym]] <- newdata[[sym]] %>% rename_with(~ gsub(paste0(sym, "."), '', .x)) return(newdata[[sym]]) # 补充返回值,修复原函数逻辑 } symbol <- setNames(symbol, symbol) newdata<-map_df(symbol, DFCONVERT, .id="symbol") CurrentPrice=c(54.41500, 95.7505, 114.26) lowline=c(40, 80, 98) highline=c(50, 90, 110) df<-data.frame(symbol, CurrentPrice, lowline, highline) # 关键:将参考线数据从宽格式转为长格式 df_long <- df %>% pivot_longer(cols = -symbol, names_to = "line_type", values_to = "y_value") ggplot(newdata) + geom_line(aes(Date, Close)) + # 将颜色、线型映射到line_type变量,触发图例生成 geom_hline(data = df_long, aes(yintercept = y_value, color = line_type, linetype = line_type)) + facet_wrap(~symbol, scales = "free_y") + # 手动指定每种线条的颜色和显示标签 scale_color_manual( values = c("CurrentPrice" = "black", "lowline" = "green", "highline" = "red"), labels = c("Current Price", "lowline", "highline") ) + # 手动指定每种线条的线型和显示标签 scale_linetype_manual( values = c("CurrentPrice" = "dotted", "lowline" = "dashed", "highline" = "dashed"), labels = c("Current Price", "lowline", "highline") ) + # 合并颜色和线型图例,避免重复显示 guides( color = guide_legend(title = "参考线"), linetype = guide_legend(title = "参考线") ) + theme( axis.text.x = element_text(size = 8, angle = 90, hjust = 0.95, vjust = 0.2), axis.text.y = element_text(size = 6), # 调整图例位置到右侧空白区域,也可设为"bottom"放在底部 legend.position = "right", legend.title = element_text(size = 10), legend.text = element_text(size = 8) )
关键改动说明
- 修复原函数逻辑:补充
DFCONVERT函数的return语句,确保能正确生成目标数据框。 - 转换数据格式:把宽格式的参考线数据转为长格式,让所有参考线共享同一结构,便于统一映射美学属性。
- 映射美学属性:在
geom_hline的aes中加入color和linetype,绑定到line_type变量,触发ggplot自动生成图例。 - 自定义图例样式:通过
scale_color_manual和scale_linetype_manual指定每种线条对应的颜色、线型和显示标签,匹配需求中的样式。 - 合并图例:用
guides把颜色和线型的图例合并为一个,避免重复显示,同时设置清晰的图例标题。 - 调整图例位置:通过
theme(legend.position)把图例放到右侧(或底部)的空白区域,不遮挡图表内容。
内容的提问来源于stack exchange,提问作者Serhat Akay
相关产品推荐
相关产品推荐

