-3

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.

enter image description here

Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
gaut
  • 5,771
  • 1
  • 14
  • 45
  • Does this answer your question? [Add legend to ggplot2 line plot](https://stackoverflow.com/questions/10349206/add-legend-to-ggplot2-line-plot) – Jonathan Jun 30 '22 at 13:09
  • as mentioned, it doesnt. The legends are wrong if I try to follow these answers, reason why i post a new question specifically for *bar* charts – gaut Jun 30 '22 at 13:10
  • 4
    it does not matter whether you have a bar or line chart; the same aesthetics apply, ggplot is build around this exact principle - also please don't post your question a second time if the first was flagged as an duplicate – Jonathan Jun 30 '22 at 13:12
  • 1
    Please do not include commentary about the workings of the site in the question body itself. If you disagree with the actions taken, instead, post a question on [Meta StackOverflow](https://meta.stackoverflow.com/). – Ian Campbell Jul 12 '22 at 20:09

1 Answers1

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

Carl
  • 4,232
  • 2
  • 12
  • 24