简体   繁体   English

如何在ggplot中的同一图例上合并颜色和填充aes

[英]How to merge color and fill aes on same legend in ggplot

I am trying to make a chart where I need to combine both fill and colour on the same legend.我正在尝试制作一个图表,我需要在同一个图例上结合填充和颜色。 The closest I have come to achieve this is the example below, but it introduces a square surrounding the line (see legend below for pce).我最接近实现这一点的是下面的示例,但它在线条周围引入了一个正方形(参见下面的图例以了解 pce)。 I have looked at combine legends for color and shape into a single legend and how to merge color, line style and shape legends in ggplot but their solutions does not seem to work for fill and colour.我已经研究了将颜色和形状的图例组合成一个图例,以及如何在 ggplot 中合并颜色、线条样式和形状图例,但它们的解决方案似乎不适用于填充和颜色。 In this case I get this square surrounding the line (see legend below).在这种情况下,我得到这个围绕线的正方形(参见下面的图例)。 I also don't want to have them all as squares as suggested in the answer to combine merge color and fill legend into one .我也不希望将它们全部作为答案中建议的正方形,以将合并颜色和填充图例合并为一个

library(tidyverse)



econ_names <-c(
  "pce",    
  "pop",    
  "psavert",
  "uempmed",
  "unemploy"
  
)



some_fills <- c(NA, "#FFB400", "#FF4B00", "#65B800", "#00B1EA")
some_cols <- c("#003299", rep(NA,4))



names(some_fills)<- econ_names
names(some_cols)<- econ_names


ggplot(data = economics_long,aes(date,value01,col = variable,fill = variable))+
  geom_col(data = subset(economics_long,variable!="pce"))+
  geom_line(data = subset(economics_long,variable=="pce"), size = 1.05)+
  scale_colour_manual(values = some_cols)+
  scale_fill_manual(values = some_fills)+
  theme_minimal()

Created on 2021-03-19 by the reprex package (v1.0.0)reprex package (v1.0.0) 于 2021 年 3 月 19 日创建

This can be fixed by setting the linetype for the columns as follows:这可以通过如下设置列的线型来解决:

ggplot(data = economics_long,aes(date,value01,col = variable,fill = variable))+
  geom_col(data = subset(economics_long,variable!="pce"), linetype = 0)+
  geom_line(data = subset(economics_long,variable=="pce"), size = 1.05)+
  scale_colour_manual(values = some_cols)+
  scale_fill_manual(values = some_fills)+
  theme_minimal() 

which produces产生

输出图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM