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

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

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

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

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