Trend graphs

The next part of the code specifies the graph of the trend in life expectancy using ggplot2. Let's look at each piece of code:

  # trend

output$trend = renderPlot({

thePlot = theData() %>%
group_by(continent, year) %>%
summarise(meanLife = mean(lifeExp)) %>%
ggplot(aes(x = year, y = meanLife, group = continent, colour = continent)) +
geom_line() + ggtitle("Graph to show life expectancy by continent over time")

if(input$linear){
thePlot = thePlot + geom_smooth(method = "lm")
}

print(thePlot)
})

The first line defines the output as a reactive plot. The second instruction uses chained dplyr instructions, as we saw in Chapter 1, Beginning R and Shiny, first to group the data by continent and year, and then to calculate the mean life expectancy in the groups that result (in Africa in each year, in America in each year, and so on). This is then sent on to a ggplot instruction for the given year on the x axis, mean life expectancy on the y axis, and the groupings/colors defined by the continent. Note that by assigning it to thePlot, we do not print it, but merely begin to build it up.

The next section tests for the value of the smoothing checkbox, input$linear, and if it is TRUE, a regression line is added to the plot. The requirement to print() ggplot graphics has been dropped from Shiny (in the first edition of this book, it was necessary for you to print() each graphic). This graphic will need to be printed in any environment, even the console, because it has not been called with ggplot(), but merely assigned to thePlot. Normally, when using ggplot() directly in a Shiny session, there will be no need to print() the plot.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset