- R Data Visualization Recipes
- Vitor Bianchi Lanzetta
- 220字
- 2021-07-02 23:33:22
How to do it...
First things first, in order to plot using ggplot2, data must come from a data frame object. Data can come from more than one data frame but it's mandatory to have it arranged into objects from the data frame class.
- We took the cars data set to fit this first graphic. It's good to actually get to know the data before plotting, so let's do it using the ?, class(), and head() functions:
> ?cars
> class(cars)
> head(cars)
- Plots coming from ggplot2 can be stored by objects. They would fit two classes at same time, gg and ggplot:
> library(ggplot2)
> plot1 <- ggplot(cars, aes(x = speed,y = dist))
Objects created by the ggplot() function get to be from classes gg and ggplot at the same time. That said, you can to refer to a plot crafted by ggplot2 as a ggplot.
- The three packages work more or less in a layered way. To add what we call layers to a ggplot, we can use the + operator:
> plot1 + geom_point()
The + operator is in reality a function.
Result is shown by the following figure:

Figure 1.2 - Simple ggplot2 scatterplot.
- Once you learn this framework, getting to know how ggvis works becomes much easier, and vice-versa. A similar graphic can be crafted with the following code:
> library(ggvis)
> ggvis(data = cars, x = ~speed, y = ~dist) %>% layer_points()
- plotly would feel a little bit different, but it's not difficult at all to grasp how it works:
> library(plotly)
> plot_ly(data = cars, x = ~speed, y = ~dist, type = 'scatter', mode = 'markers')
Let's give these nuts and bolts some explanations.