rovyko
rovyko

Reputation: 4577

Add simple histogram to legend in ggplot2

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?

Upvotes: 1

Views: 230

Answers (1)

chemdork123
chemdork123

Reputation: 13803

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

Upvotes: 1

Related Questions