Change legend in ggplot

library(tidyverse)
set.seed(5L)
dat <- tibble(year = 1:5, x = rnorm(5L), y = - rnorm(5L)) %>% 
  mutate(z = x + y)

ggplot(dat) +
  geom_bar(aes(year, x, fill = "Exports"), stat = "identity") + 
  geom_bar(aes(year, y, fill = "Imports"),  stat = "identity") + 
  geom_line(aes(year, z) , size = 1.2, color = "firebrick4") +
  geom_point(aes(year, z, fill = "Trade Balance"), size = 2, color = "firebrick4") +
  theme(axis.ticks.x = element_line(colour = "black", size = 1),
    axis.ticks.y = element_line(colour = "black", size = 1), 
    axis.ticks.length = unit(.25, "cm"), 
    axis.text = element_text(colour = "black", size = 10),
    axis.title = element_blank(),
    panel.background = element_rect(fill = "transparent"),
    panel.grid = element_blank(), 
    legend.position= "top") + 
  scale_fill_manual(name = "",
                    values = c("Exports" = "deepskyblue3", 
                               "Imports" = "lightskyblue3", 
                               "Trade Balance" = "firebrick4"),
                    guide = guide_legend(override.aes = aes(colour = NA)))

I want to show the Trade Balance in the legend as line with dots.
Thanks

Hi melgoussi,
one approach to achieve this is by adding a color legend and adjust the spacing between the legends via theme options legend.spacing and legend.margin so that it looks as if there is only one legend. This way you can also get rid of the adjustments via guide_legend:

library(tidyverse)
set.seed(5L)
dat <- tibble(year = 1:5, x = rnorm(5L), y = - rnorm(5L)) %>% 
  mutate(z = x + y)

ggplot(dat) +
  geom_bar(aes(year, x, fill = "Exports"), stat = "identity") + 
  geom_bar(aes(year, y, fill = "Imports"),  stat = "identity") + 
  geom_line(aes(year, z, color = "Trade Balance") , size = 1.2) +
  geom_point(aes(year, z, color = "Trade Balance"), size = 2) +
  scale_fill_manual(values = c("Exports" = "deepskyblue3", 
                               "Imports" = "lightskyblue3")) +
  scale_color_manual(values = c("Trade Balance" = "firebrick4")) +
  labs(fill = NULL, color = NULL) +
  theme(axis.ticks.x = element_line(colour = "black", size = 1),
        axis.ticks.y = element_line(colour = "black", size = 1), 
        axis.ticks.length = unit(.25, "cm"), 
        axis.text = element_text(colour = "black", size = 10),
        axis.title = element_blank(),
        panel.background = element_rect(fill = "transparent"),
        panel.grid = element_blank(), 
        legend.position= "top",
        legend.spacing = unit(0, "pt"),
        legend.margin = margin(l = 0, r = 0),
        legend.key = element_rect(fill = NA))

Created on 2020-10-11 by the reprex package (v0.3.0)

1 Like

for a line with dots you can try linetype 3

geom_line(aes(year, z, color = "Trade Balance"),linetype=3 , size = 1.2)