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

How it works...

Beginning with step 1, geom_quantile() is used to draw quantile regression lines with ggplot2. Argument quantiles must be inputted with a vector describing which quantiles may be drawn. Arguments colour and size pick lines' colors and sizes respectively. Also, it is important to outline the function ylim(), which limits the graph range so that the lines won't go to infinity and beyond.

Note that geom_point's points were reduced using the reference shape = '.'.

Next, step 2 shows how to fit quantile regressions using the quantreg package. Function rq() adjusts the regression, argument tau rules the desired quantile. Function  rq() is inputted into fitted() function, this way we get only the fitted values from quantile regression.

Do not forget that diamonds data frame comes from ggplot2.

Finally, step 3 draws about the same lines using plotly. Right after loading the package, an object called c (color) is created. This is object is supposed to work later as a shortcut for the color black. Afterwards, plot_ly() function draws the scatterplot.

Subsequently, several add_lines() functions are chained by %>%, each function adding a specific quantile line. Note how our earlier c object is calling for the black color while it saves some space; also notice how markers are removed by setting marker = NULL.

In the end, layout() is called in order to set the limits of the y axis, thus avoiding lines going far far away. Brewing similar results with ggvis would require a little bit more code but definitely can be done. Here lies a challenge for the reader. Now let's craft a publish-quality scatterplot.