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.
Usually layers are created using geom_* or stat_* calls but it can also be created directly using this function.
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.
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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With