Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add another layer / new series to a ggplot?

Tags:

r

ggplot2

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.

like image 548
John Avatar asked Feb 24 '10 21:02

John


People also ask

What symbol is used to add another layer to a Ggplot?

Usually layers are created using geom_* or stat_* calls but it can also be created directly using this function.

How many layers are there in Ggplot?

Altogether, seven layers can be used in ggplot, but the three mentioned above are the minimum needed for ggplot to work. The seven layers constitute what Wickham calls “the layered grammar of graphics.” There can be many types of each element.

Can you use two datasets in Ggplot?

This section shows how to use the ggplot2 package to draw a plot based on two different data sets. For this, we have to set the data argument within the ggplot function to NULL. Then, we are specifying two geoms (i.e. geom_point and geom_line) and define the data set we want to use within each of those geoms.

What are the correct layers of variables in Ggplot?

There are three layers in this plot. A point layer, a line layer and a ribbon layer. Let us start by defining the first layer, point_layer . ggplot2 allows you to translate the layer exactly as you see it in terms of the constituent elements.


1 Answers

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") 
like image 66
hadley Avatar answered Sep 28 '22 05:09

hadley