Drawing a simple contour plot using ggplot2
Contour plots draw lines to represent levels between surfaces. As with other 3D representations, we now need three variables, x, y, and z, and speaking for ggplot2
, data frame must display a single row for each unique combination of x and y. That is why it's easier to bring these visuals by applying 2D kernel density estimations -- there is a single row for each unique combination of x and y.
This recipe will demonstrate a very easy way to create and plot those estimates by drawing contour plots with ggplot2
. We will be using variables speed
and dist
from car
data frame to draw this plot. Recipe highlights the very basics of making a contour plot understandable while it teaches how to improve this visual by drawing filled polygons instead of empty curves.
How to do it...
We proceed as follows for the recipe:
- Call for
geom_density_2d()
in order to compute the 2D kernel density estimates and draw curves:
> library(ggplot2) > ggplot(data = cars...