Get startedGet started for free

htmlwidgets

1. htmlwidgets

We've talked about a few of the R packages that produce web-friendly graphs. There are many more packages that make web-friendly visualizations beyond traditional graphs. This whole category of packages is called htmlwidgets.

2. What's an htmlwidget?

htmlwidgets are based on a framework that connects R and javascript. R developers use this framework to create R packages that allow you to take advantage of all kinds of Javascript capabilities with nothing but R code. All of these visualizations are web-friendly and work beautifully as components of flexdashboards. You can learn more at the htmlwidgets website.

3. htmlwidget: leaflet

Each htmlwidget package requires a bit of learning. You've already learned how to use one in the last lesson: plotly! In this lesson we're going to learn how to use another popular htmlwidget - the leaflet package. This package will allow you to add visually appealing interactive maps with data to your dashboard.

4. leaflet basics

The simplest use of leaflet is when you have a dataset with latitude and longitude coordinates in columns. In this case, you only need to call the leaflet() function to initiate the widget, and then add two layers: one for map tiles (which show the actual map in the background), and one to represent the latitude and longitude data (such as the addMarkers() layer in this example). This will create an interactive map with markers at the latitude and longitude coordinates.

5. leaflet with Dataframes

A nice feature of leaflet and many other htmlwidgets is that they are designed to work well with dataframes in R. A dataframe can be passed to the leaflet function and it will be used for the layers added to the widget. Leaflet also has some helpful defaults: for example, it identifies latitude and longitude columns by name if it can. The code here produces the same map as the code on the previous slide, but this time we're sending data_df to leaflet(), and it uses the longitude and latitude columns to add the markers by default.

6. Let's practice!

The leaflet package is very powerful and can do much more than plot markers on a map as we just discussed. If maps are important to you, consider learning more about leaflet by following the link on the htmlwidgets website. Now let's practice making leaflet maps!