Børge Klungerbo
Børge Klungerbo

Reputation: 177

ggplot + geom_point + legend based on both size and color

Is there a way to display both size and color in the legend when using geom_point?

library(ggplot2)
cons2 <- data.frame(
  value_date  = as.Date(c('2013-04-30', '2013-04-30', '2013-06-13', '2013-06-13')),
  ticker = c('AAPL','FTW','AAPL','FTW'),
  discount = c(0.34,0.10,0.25,0.20),
  b = c(0.40,0.55,.60,0.90),
  yield = c(0.08,0.04, 0.06,0.03)
)

p <- ggplot(cons2)
p <- p + geom_point(aes(yield,b, size = discount, color=value_date))
p

This plot will only show size(discount) in the legend, but I would like to display both size(discount) and color(value_date).

Upvotes: 3

Views: 907

Answers (2)

hadley
hadley

Reputation: 103918

For some reason ggplot2 isn't automatically figuring out that it needs the date frame. Try telling it explicitly:

ggplot(cons2) +
  geom_point(aes(yield, b, size = discount, color = value_date)) +
  scale_colour_gradient(trans = "date")

Upvotes: 1

joran
joran

Reputation: 173587

ggplot2 doesn't know quite what to do with the Date class. Try:

color=factor(value_date)

instead.

Upvotes: 3

Related Questions