Plotting in R

Nextjournal’s default R environment comes with the ggplot2 and plotly packages pre-installed. It also includes tidyverse and more to ease working with numerical data. Simply make them available via library(<package name>).

The following examples show how to plot temperature predication data in various scenarios for the Chicago area based on a subset of the OpenNEX DCP30 dataset.

OpenNEX-chicago-climate.csv

Inspecting Data Frames

Inspecting their contents often comes handy when working with data frames. Simply returning a data frame will produce a table viewer that makes it easy to browse the data frame’s contents:

library(tidyverse)
data <- read_csv(
OpenNEX-chicago-climate.csv
) head(data, n=30)
0 items

ggplot2

Check out ggplot2’s documentation for more examples.

library(tidyverse)

# Read in CSV
data <- read_csv(
OpenNEX-chicago-climate.csv
) group <- data %>% mutate( year = update(Date, day=1, month=1), # Reset dates to beginning of year temp = Value - 273.15 # Convert Kelvin to Celsius ) %>% group_by(year, Scenario) %>% # Group by year and scenario summarise(max_temp=max(temp)) # Pick the max temp for each group model <- first(data["Model"]) title <- paste("Maximum mean temperature for warmest month using model", model) # Returning the plot tells Nextjournal to display it ggplot(group, aes(x = year, y = max_temp)) + geom_line(aes(color = Scenario)) + labs( title = title, x = "Years", y = "Temperature [Celsius]" )

Plotly

Check out plotly’s documentation for more examples.

library(plotly)

# Read in CSV
data <- read_csv(
OpenNEX-chicago-climate.csv
) group <- data %>% mutate( year = update(Date, day=1, month=1), # Reset dates to beginning of year temp = Value - 273.15 # Convert Kelvin to Celsius ) %>% group_by(year, Scenario) %>% # Group by year and scenario summarise(max_temp=max(temp)) # Pick the max temp for each group model <- first(data["Model"]) title <- paste("Maximum mean temperature for warmest month using model", model) # Returning the plot tells Nextjournal to display it plot_ly( group, x = ~year, y = ~max_temp, color = ~Scenario, type = "scatter", mode = "line" ) %>% layout( title = title, xaxis = list(title = "Years"), yaxis = list (title = "Temperature [Celsius]") )
Loading viewer…