Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading