Creating simple raster plots with ggplot2
Raster plots can be seen as optimized tile plots. By adopting this geometry, there is no need to pick the binwidth
argument. This makes the plot brewing process easier sometimes. It may be faster than brewing tiles while it also produces a smaller output when saved to PDF.
The ggplot2
documentation considers raster geometry as a high performance special case when all tiles are the same size. This recipe demonstrates how to craft a simple raster plot with ggplot2
. Using the car
data set, a third variable will be computed by the stat_density_2d()
function and then used to fill the raster. Explanations are highlighting alternative functions.
How to do it...
Here is how we proceed with the recipe:
- To simultaneously compute
..density..
and plot a raster, usestat_density_2d()
:
> library(ggplot2) > ggplot(data = cars, aes(x = speed, y = dist)) + stat_density_2d(aes(fill = ..density..), geom = 'raster', contour = F)
Result looks like...