jnordeman
jnordeman

Reputation: 139

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). 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. 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)

Upvotes: 2

Views: 1077

Answers (1)

Miff
Miff

Reputation: 7941

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

Output figure

Upvotes: 1

Related Questions