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

Add legend to ggplot2 bar plot

note that this question differs from Add legend to ggplot2 line plot. This is a multiple bar plot and the answers provided for line plots dont apply.

How can I add a legend to the below?

library(tidyr);library(ggplot2)   
date <- 2001:2050
dat1 <- 1:50
dat2 <- 50:1
data <- tibble(date, dat1, dat2)
p2 <- ggplot(data, aes(x=date)) +
  geom_bar(aes(y=dat1, color = "orange"), stat = "identity", fill="orange")+
  geom_bar(aes(y=dat2,color = "blue"), stat = "identity", fill="blue")+
  ggtitle("dat") + 
  ylab("unit") 
p2

As you can see the default legends and bars are wrongly filled.

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

enter image description here

This was closed wrongfully, again.

>Solution :

library(tidyverse)

date <- 2001:2050
dat1 <- 1:50
dat2 <- 50:1
data <- tibble(date, dat1, dat2)

data %>%
  pivot_longer(c(dat1, dat2)) %>%
  ggplot(aes(date, value, fill = name)) +
  geom_col(position = position_identity())+
  scale_fill_manual(values = c("orange", "blue")) +
  ggtitle("dat") + 
  ylab("unit") +
  theme(axis.text.x = element_text(angle = 45, vjust = 0.5, hjust=1))

Created on 2022-06-30 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