Plotly is a d3 based graphing library used to produce interactive and high quality graphs in R. In the following exercises, we will look at some advanced plots and features avaialable in the package. Please note that the list here is not exhaustive.
We will use datasets available in base R packages.
You are expected to have the knowledge of generating basic plots using plotly package before attempting this exercise set. It is recommended that you go through this exercise set to test your knowledge on plotly basics.
Answers to the exercises are available here.
Install and load the latest version of
Generate separate histograms for the first four columns of
iris dataset and save the plots in objects
plot_ly() function with
x argument and
name argument to give appropriate name for the trace.
subplot() function to generate a plot with all the plot objects from previous exercise as the arguments.
b. Use the
nrows argument to arrange 2 plots per row.
a. Generate a scatter plot for the iris dataset with first column on the x-axis and second column on the y-axis. Save the plot object.
b. Generate a 2d histogram using the add_histogram2d() function.Save the plot object.
HINT: Use the function
plot_ly() with the same
y arguments and pass the plot object to the 2-d histogram function.
Generate a subplot with the scatter plot and the 2-d histogram created in the previous exercise.
Notice how the scatter plot can be represented in a more interesting way. Cells in the 2-d histogram are binned and represented with the color on the scale based on the cell population/density.
Set the value of
shareY arguments in the
subplot() function to scale the plots to the same range of
Now, let us build a 3-d surface plot. The syntax to build such plot is as below.
plot_ly(z = matrix(1:100, nrow = 10)) %>% add_surface()
Click, hold and drag the cursor to see the plot surface.
Build a 3-d surface plot using the
volcano dataset available in the base R distribution.
Let’s look at few helpful and commonly used arguments from the
Create and save a scatter plot object with first and second columns of iris dataset as
y arguments respectively. Colour the markers based on the
a. Add an appropriate title to the plot using the
layout function and
b. Add an appropriate x-axis label using the
xaxis takes a list of attribute values. Refer to the R reference page for more help.
c. Add an appropriate y-axis label.
a. Use the
range attribute in the list of values given to the
xaxis argument to set the x-axis range from 1 to 10.
b. Similarly, set the y-axis range from 1 to 5.
Try different layout options to further customize the font, axes etc… of the plot.