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

How it works...

First step begins by defining the seed generator, this way you get the same result I get from geom_jitter(). After loading ggplot2, the same step is creating and working an object called rug. It starts by receiving a ggplot with only some aesthetics declared and no geometry.

Aesthetics declared into ggplot() function are later inherited other ones, unless we change them. Subsequently, rug is receiving two geometries: geom_jitter() and geom_rug(). Calling geom_jitter() it's equivalent to geom_point( position = 'jitter'). Function geom_rug() is drawing rug plots in the margins.

Both rugs and points do suffer with over-plotting. Chosen solution was to combine jitter and alpha blending. Argument alpha had set the last technique for both geometries. Tweak position argument at geom_rug() function to ask for jittered rugs (points are already jittered once recipe used geom_jitter()).

Finally, calling rug will display the result. Note that the colors match for both points and rugs. Also notice that there are no legends to explain the rugs. That happened because we called show.legend = F inside geom_rug().

Last step is conducting a simply coercion from a ggplot object to an interactive plotly one. Coercion may work for some geometries and not for others. For this particular one, it works. The only thing needed is to call plotly::ggplotly(). If no plot object is inputted, it shall display the last ggplot object called. It's a good practice to set height and width arguments.