1

Given a ggplot plot generated using the following code

size = 10000
d = data.frame(
  type = rep(c("A","B","C"), each=size),
  val = c(rnorm(size, 0, 1), rnorm(size, 1, 2),rnorm(size, 2, 3))
)

require(ggplot2)
(
  ggplot(subset(d, is.element(type, c("A", "C"))), aes(x=val))
  + geom_histogram(aes(y=..density..), bins=100, position="identity", alpha=0.5)
  + geom_line(aes(color=type), stat="density", size=1)
)

Is it possible to add a grey square with a custom label representing the simple histogram to the legend? Can it be done without creating a dummy item?

rovyko
  • 4,068
  • 5
  • 32
  • 44

1 Answers1

1

All you need is to put fill= into aes() for the geom_histogram() line. You don't have a column in your dataset to assign to this, but if you assign fill="string name" in aes(), then ggplot will create a fill legend with that as the label.

Of course, the color will default to the ggplot "red" color, so if you want to go with gray again, you have to set that with scale_fill_manual(), since fill= outside aes() will overwrite anything you put within aes().

ggplot(d, aes(x=val)) + 
  geom_histogram(aes(y=..density.., fill='histogram'),
    bins=100, position="identity", alpha=0.5) +
  geom_line(aes(color=type), stat="density", size=1) +
  scale_fill_manual(values='gray20')

enter image description here

chemdork123
  • 12,369
  • 2
  • 16
  • 32
  • Great! Is there any way to change the word `fill` in the legend to something else or remove it entirely? – rovyko Jun 28 '20 at 04:19
  • 1
    Sure, just add that to the `name=` argument of `scale_fill_manual()`. So `scale_fill_manual(name="My Legend Title", values="gray20")` would give you the same plot with the legend title changed. To remove, you can just include `""`, but that will keep the line for the legend title, so to remove I would set `name=NULL`. – chemdork123 Jun 28 '20 at 06:27