Reader 123
Reader 123

Reputation: 367

Grouped densities over histogram - how to remove density marker from legend? (Ggplot, R)

Reproducible example:

require(ggplot2)

mtcars$am2 <- factor(mtcars$am)
p1 <- ggplot(mtcars, aes(x = mpg, y = ..density.., fill = am2)) +
  geom_histogram(position = "identity", alpha = 0.8, colour = 1, bins = 12)+
  scale_fill_manual(values = c( "pink", "lightgrey")) +
  theme(
    legend.position = "bottom"
  )

p1 +
  geom_density(colour = "blue", lwd = 2, inherit.aes = F, aes(x = mpg, y = ..density.., group = am2))

I would like to remove the thick blue border from around the squares representing the colours in the legend. (In my real data this makes sense, the two densities don't overlap.) I have tried to play with legend.key = this and that in theme(), but nothing seems to take effect. Can anyone help, please?

Upvotes: 0

Views: 267

Answers (2)

Shubham
Shubham

Reputation: 357

Add show_guide = FALSE in geom_density:

mtcars$am2 <- factor(mtcars$am)
p1 <- ggplot(mtcars, aes(x = mpg, y = ..density.., fill = am2)) +
  geom_histogram(position = "identity", alpha = 0.8, colour = 1, bins = 12)+
  scale_fill_manual(values = c( "pink", "lightgrey")) +
  theme(
    legend.position = "bottom"
  )

p1 +
  geom_density(colour = "blue", lwd = 2, inherit.aes = F, show_guide = FALSE, aes(x = mpg, y = ..density.., group = am2))

Upvotes: 1

Quinten
Quinten

Reputation: 41523

You could use show.legend=FALSE in your geom_density call to remove the blue border in your legend like this:

mtcars$am2 <- factor(mtcars$am)
library(ggplot2)
p1 <- ggplot(mtcars, aes(x = mpg, y = ..density.., fill = am2)) +
  geom_histogram(position = "identity", alpha = 0.8, colour = 1, bins = 12)+
  scale_fill_manual(values = c( "pink", "lightgrey")) +
  theme(legend.position = "bottom") 

p1 +
  geom_density(colour = "blue", lwd = 2, inherit.aes = F, aes(x = mpg, y = ..density.., group = am2), show.legend = FALSE)

Created on 2022-10-15 with reprex v2.0.2

Upvotes: 2

Related Questions