Get startedGet started for free

Layering in plotly

1. Adding layers

You've seen how to create and polish animations. Now, you'll learn how to build them by layering traces, much like you layer geometries in ggplot2.

2. Why layer?

To understand why you might want to layer traces in the context of an animation, let's revisit the animation from the previous lesson. In the last lesson, we polished the slider text to display the year; however, this requires the viewer to divert attention from the plot. An alternative approach is to print the year as the first layer of the plot, followed by the data points.

3. Text layer

We create the first layer as we have throughout this lesson: by creating the canvas via the plot_ly() command, followed by the trace we wish to add to the plot. Here, our canvas maps income to the x-axis and co2 to the y-axis. Since we want the year to be printed in the background, we first add a text trace, setting the x- and y-coordinates to a single point and mapping the year to the text and frame aesthetics. Finally, we adjust the font by passing a list of attributes. We set the font size to 150 and the color to gray80. Recall that we must use the toRGB() command to translate R-specific color names, like gray80 and steelblue, for use with plotly.

4. Points layer

Now that we have a canvas with the desired background text for each frame, we add points to our scatterplot using the markers trace. Here we map year to the frame and country to the ids to animate the scatterplot. As in our previous animations we apply a log transformation to both axes using the layout() command.

5. Polishing

Finally, we remove the slider text using the animation_slider() command and the legend by setting showlegend equals FALSE in the layout() command.

6. The result

Here's the polished chart with the year plotted in the background. While this type of layering is useful in animation, it's more-generally useful, so keep it in mind when you are creating all of your interactive graphics.

7. Let's practice!

Now, it's time to apply what you learned to the state economic index data.

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.