library(readr) # data import library
library(dplyr) # library for using the pipe operator "%>%"
library(plotly)
# Loading data from the internet
<- "https://raw.githubusercontent.com/owid/co2-data/master/owid-co2-data.csv"
url <- read.csv(url)
co2_data
# Filtering data for Brazil using subset()
<- subset(co2_data, country == "Brazil")
co2_brasil
# Creating an interactive graph with plot_ly
<- plot_ly(data = co2_brasil, x = ~year, y = ~co2, type = 'scatter', mode = 'lines+markers') %>%
co2_plot layout(title = "CO2 emissions in Brazil over the years",
xaxis = list(title = "Year"),
yaxis = list(title = "CO2 emissions (million tons)"))
More interactivity!
Objectives:
1. Observe the extensive interaction capabilities of the “plotly” package
2. Create a graph with a slider
3. Create a graph with a drop-down menu
So far, we have only “scratched the surface” of the graphical interactivity potential of the
plotly
package. As already mentioned, this library allows for a wide range of user actions, such as sliders, drop-down menus, and buttons, among many others.
1 Adding a range slider
A slider of this nature allows you to choose a data window for a more detailed study in that region. In this case, it is possible to add a range slider to a simple graph.
We can illustrate its use by observing greenhouse gases, and in particular, carbon dioxide emissions in Brazil from an internet database. To do this, you will learn how to obtain a file from an internet database, filter it to a desired subset, and draw the resulting graph with an additional slider.
1.1 CO\(_{2}\) emissions and the greenhouse effect
Emissions of CO\(_{2}\) and other gases from the burning of fossil fuels are largely responsible for the greenhouse effect, directly affecting climate change. To reduce these emissions, it is necessary to transform the current energy matrix, industry, and food systems.
To understand CO\(_{2}\) emissions in Brazil from 1890 to 2022, run the following code snippet in an R script (i.e., copy, paste, and run) from the source Our World in Data.
Now, the icing on the cake. The insertion of a slider to select ranges for a more focused study.
%>%
co2_plot rangeslider()
You can copy and paste the scripts in sequence for execution, or just add the command
rangeslider()
with the pipe operator %>% at the end.Now try positioning the mouse on one of the two side markers of the lower graph, dragging it, and observe the result. The slider can be useful when you want to focus on a specific region of the graph. For example, to adjust CO₂ emissions for the last few years.