Pivoted data with ggplot lines and stacked bars

Consider the following chart:

library(lubridate)
library(dplyr)
col1 <- col2 <- col3 <- c(1:5)
col4 <- c(11:15)
date <- as_date("2022-07-27")+0:4
data <- data.frame(date, col1, col2, col3, col4) %>% pivot_longer(all_of(c("col1", "col2", "col3", "col4")))

p1 <- ggplot(data, aes(fill=name, y=`value`, x=`date`)) +
  geom_bar(position="stack", stat="identity") +
  ylab("MCHF")+
  ggtitle("mytitle")+
  theme(legend.position="bottom",
        legend.key.size = grid::unit(0.1, "inch"),
          legend.key.width = grid::unit(0.1, "inch"))+
  ggplot2::guides(fill=ggplot2::guide_legend(ncol=3))
p1

plot1

How can I have col4 plotted as a line instead of being part of the stacked bar chart? Ideally I’d like to keep it in the legend.

>Solution :

You could remove "col4" from your pivot_longer and add a geom_line for your "col4" like this:

library(lubridate)
library(ggplot2)
library(tidyr)
library(dplyr)

col1 <- col2 <- col3 <- c(1:5)
col4 <- c(11:15)
date <- as_date("2022-07-27")+0:4
data <- data.frame(date, col1, col2, col3, col4) %>% pivot_longer(all_of(c("col1", "col2", "col3")))

p1 <- ggplot(data, aes(fill=name, y=`value`, x=`date`)) +
  geom_bar(position="stack", stat="identity") +
  geom_line(aes(x = date, y = col4, group = 1, colour = "col4")) +
  ylab("MCHF")+
  ggtitle("mytitle")+
  theme(legend.position="bottom",
        legend.key.size = grid::unit(0.1, "inch"),
        legend.key.width = grid::unit(0.1, "inch"))+
  scale_colour_manual(name= "", values = 1) +
  ggplot2::guides(fill=ggplot2::guide_legend(ncol=3))
p1

Created on 2022-07-27 by the reprex package (v2.0.1)

Leave a Reply