Home > OS >  How to get rid of a gray filling in a ggplot graph legend (stacked bar)
How to get rid of a gray filling in a ggplot graph legend (stacked bar)

Time:07-19

I am having troubles fixing a legend in my ggplot chart. I would like to get rid of the gray filling and have a square filled with the color assigned to a variable.

data = data.frame(Date = (seq(as.Date("2018-02-03"), as.Date("2019-05-05"), by = "days")),
                  var1 = runif(457),
                  var2 = runif(457)) %>%
    tidyr::pivot_longer(-Date, names_to = "variable", values_to = "value")

ggplot(data = data, 
           aes(x = Date, y = value, colour = variable))   
        geom_bar(stat = 'identity')   
        theme_minimal()  
        scale_color_manual(values = c("#A90046", "#D1EAFE"), name = "")

enter image description here

CodePudding user response:

You could change aesthetic to fill and scale_fill_manual like this:

library(tidyr)
data = data.frame(Date = (seq(as.Date("2018-02-03"), as.Date("2019-05-05"), by = "days")),
                  var1 = runif(457),
                  var2 = runif(457)) %>%
  tidyr::pivot_longer(-Date, names_to = "variable", values_to = "value")

library(ggplot2)
ggplot(data = data, 
       aes(x = Date, y = value, fill = variable))   
  geom_bar(stat = 'identity')   
  theme_minimal()  
  scale_fill_manual(values = c("#A90046", "#D1EAFE"), name = "")

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

  • Related