Load data and Libraries

https://r4ds.had.co.nz/data-visualisation.html

if (!("ggplot2" %in% installed.packages())) {
    install.packages('ggplot2')
}
library('ggplot2')
## Warning: package 'ggplot2' was built under R version 4.4.1
if (!("devtools" %in% installed.packages())) {
    install.packages('devtools')
}
if (!("tidyr" %in% installed.packages())) {
    install.packages('tidyr')
}
library(tidyr)
if (!("dplyr" %in% installed.packages())) {
    install.packages('dplyr')
}
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
#devtools::install_github('neuhausi/canvasXpress')
#devtools::install_local("~/git/canvas/R/canvasXpress.tar.gz")
#devtools::install_local("~/git/canvas/R/canvasXpress.tar.gz", build_manual = TRUE, upgrade = "always")
library('canvasXpress')

geom_line() is suitable for time series

g <- ggplot(economics, aes(date, unemploy)) + geom_line()
g

canvasXpress(g)

geom_line() is suitable for time series – by color

eco <- economics_long
colnames(eco)[2] <- "vari"
g <- ggplot(eco, aes(date, value01, colour = vari)) + geom_line()
g

canvasXpress(g)

geom_step() is useful when you want to highlight exactly when the y value changes

recent <- economics[economics$date > as.Date("2013-01-01"), ]
g <- ggplot(recent, aes(date, unemploy)) + geom_line()
g

canvasXpress(g)

geom_step() is useful when you want to highlight exactly when the y value changes

g <- ggplot(recent, aes(date, unemploy)) + geom_step()
g

canvasXpress(g)

Basic line plot

g <- ggplot(data = economics, aes(x = date, y = pop))+ geom_line(color = "#00AFBB", size = 2)
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
g

canvasXpress(g)

Plot multiple time series data

df <- economics %>%
  select(date, psavert, uempmed) %>%
  gather(key = "variable", value = "value", -date)
colnames(df)[2] <- "vari"
g = ggplot(df, aes(x = date, y = value)) + geom_line(aes(color = vari), size = 1) + scale_color_manual(values = c("#00AFBB", "#E7B800"))
g

canvasXpress(g)

Set date axis limits

min <- as.Date("2002-1-1")
max <- NA
g <- ggplot(data = economics, aes(x = date, y = psavert)) + geom_line(color = "#00AFBB", size = 1) + scale_x_date(limits = c(min, max))
g
## Warning: Removed 414 rows containing missing values or values outside the scale range
## (`geom_line()`).

canvasXpress(g)

Add trend smoothed line

g <- ggplot(data = economics, aes(x = date, y = psavert)) + geom_line(color = "#00AFBB", size = 1) + stat_smooth(color = "#FC4E07", method = "loess")
g
## `geom_smooth()` using formula = 'y ~ x'

canvasXpress(g)
## `geom_smooth()` using formula = 'y ~ x'