34

In ggplot I can add a series to a plot with:

ggplot(diamonds, aes(x = carat, y = price)) + geom_point()

How do I simply add another series, e.g. plotting the cost of rubies against diamonds. Assuming rubies was also in the diamonds dataset. I have tried to lay over the top another layer with the rubies data, but it just plots the rubies and not the diamonds/carat.

ggplot(diamonds, aes(x = carat, y = price)) + geom_point() + aes(x = rubies, y = price)

I can see that this would be possible by melding all the data together first, ready to plot it, so maybe I should go down that route. However, just adding another series to a plot like this seems like it should not be too hard, but I can't figure out how to do it.

John
  • 5,139
  • 19
  • 57
  • 62

1 Answers1

62
rubies  <- data.frame(carat = c(3, 4, 5), price= c(5000, 5000, 5000))

ggplot(diamonds, aes(carat, price)) + 
  geom_point() + 
  geom_point(data = rubies, colour = "red")
hadley
  • 102,019
  • 32
  • 183
  • 245
  • 1
    What if you want to add a 2nd series of points *and* a second line pertaining to those new points? For example, if you already have `ggplot(dat,aes(X,Y)) + geom_point() + geom_line()` and you want to add both a 2nd `geom_point` and a 2nd `geom_line` ? – theforestecologist Jul 12 '17 at 00:24
  • 1
    do I have to repeat the 2nd data set and variable list for both geom objects, or is there a better way? – theforestecologist Jul 12 '17 at 00:37
  • why does it throw an aesthetics length error when you code it like: ggplot(diamonds, aes(diamonds$carat, diamonds$price)) + geom_point() + geom_point(data = rubies, colour = "red") – Mark Oct 19 '18 at 22:00
  • To add a second geom_line see this answer: https://stackoverflow.com/a/5323178/2682264 – dpel Jul 16 '19 at 09:01
  • @Mark simply because `diamonds` contains more rows than `rubies` The answerer shows how `rubies` is constructed in the first line, and there you can see it only contains three rows. Moreover, you shouldn't use `table$row` syntax in aesthetic mappings. – Zimano Mar 19 '20 at 12:27