R Data Visualization Recipes
上QQ阅读APP看书,第一时间看更新

How it works...

Step 1 brings the ggplot2 scatterplot alive. It starts by loading the package using library(). Then an object name sca1 (scatterplot 1) is created, storing the recently created ggplot type object. It carries data and basic aesthetics (x and y), all required in order to make a scatterplot.

Next, sca1 is called and summed up with geom_point() to pick the point geometry. Until now no novelties, the only one is the ggtitle() function, stacked to add a title inside the plot. Normally, those are displayed on the outside, although sometimes it's good to have them at the inside.

Default ggplot2 title is left aligned. Add theme(plot.title = element_text(hjust = .5)) to have the title centered.

Subsequently, step 2 draws a similar but interactive version of the plot drawn by the previous step. A little different from what is done by ggplot2, here the geometry was picked by the very same function responsible for initializing the plot object (plot_ly()). This can be done in a more interactive way by trusting add_traces() or add_markers() functions after this first one.

Entire plot was designed by plot_ly() alone, and then stored into the sca2 object. By choosing type = 'scatter', the marker mode was enabled, giving away a scatterplot. The yet unused layout() function joined the code with the aid of pipe operator (%>%). The title argument carried the string to be displayed as title.

Step 3 introduces a new way to create a ggvis type object. Rather than directly inputting data as first argument, pipe operator (%>%) declared data argument. Arguments x and y were called in the sequence and their names could be omitted once they were called in the right order.

Pipe operator (%>%) hands previous object or function results to work as the first argument to the next function. It's not a base R operator, but it's very famous and is carried by many packages, such as ggvisplotly and dplyr. Strictly, it's not an operator but a function used to chain a series of functions.

Out of curiosity, when the geometry is missing, ggvis takes care of guessing one. Try entering sca3 into your console to see the guessing taking place.