Get startedGet started for free

Graphs

1. Graphs

In this lesson, we'll talk about the element you're mostly likely to use in your dashboard: graphs.

2. Adding graphs: the basics

The easiest way to get a graph of any kind into your dashboard is just to add the code for the graph to an R chunk, and put that R chunk in a flexdashboard chart. You already did this in an exercise in the last chapter! In this sample code we're using base graphics, but any type of plot you can make in R will work.

3. Static graphs do not flex

The types of R graphs you're most likely to be familiar with are static graphs. These are what's produced by base graphics, and ggplot2 among others. These graphs can definitely be included in flexdashboards, but there are a few things to be aware of. One of the great things about flexdashboard is that it automatically sizes components to "flex" and fit nicely in their container, even as a user resizes the page. Static graphs are sized to fit the container in one dimension, but the aspect ratio (the ratio of width to height) is preserved. This can mean that your graph fills the chart height, but not the width.

4. Resizing graphs

One way to solve this problem is to specify the width and height of the graph to fit the flex container as closely as possible. You can do this with the fig.width and fig.height arguments for the associated R chunk.

5. Resizing graphs

So this works, but there are three downsides. First, it takes some trial and error to find the right width and height settings. Second, if you add or remove charts from your dashboard page, you'll have to adjust the settings for other charts again. Third and most importantly, when the viewer of your dashboard resizes their browser window, your graph will no longer fit nicely in the box. In the next lesson we'll talk about an alternative that solves these problems.

6. Let's practice!

Now let's try some examples.