library('tidyverse')
── Attaching packages ─────────────────────────────────────── tidyverse 1.2.1 ── ✔ ggplot2 3.2.0 ✔ purrr 0.3.2 ✔ tibble 2.1.3 ✔ dplyr 0.8.3 ✔ tidyr 0.8.3 ✔ stringr 1.4.0 ✔ readr 1.3.1 ✔ forcats 0.4.0 ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ── ✖ dplyr::filter() masks stats::filter() ✖ dplyr::lag() masks stats::lag()
ggplot2 generates static charts.
options(repr.plot.width = 4, repr.plot.height = 3)
p = ggplot(mpg, aes(x = displ, y = cty))
p = p + geom_point()
p
We can interrogate other observation properties with mappings.
options(repr.plot.width = 5, repr.plot.height = 3)
p = ggplot(mpg, aes(x = displ, y = cty, color = class))
p = p + geom_point()
p
But, we have lots of properties.
print(mpg)
# A tibble: 234 x 11 manufacturer model displ year cyl trans drv cty hwy fl class <chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr> 1 audi a4 1.8 1999 4 auto(l… f 18 29 p comp… 2 audi a4 1.8 1999 4 manual… f 21 29 p comp… 3 audi a4 2 2008 4 manual… f 20 31 p comp… 4 audi a4 2 2008 4 auto(a… f 21 30 p comp… 5 audi a4 2.8 1999 6 auto(l… f 16 26 p comp… 6 audi a4 2.8 1999 6 manual… f 18 26 p comp… 7 audi a4 3.1 2008 6 auto(a… f 18 27 p comp… 8 audi a4 quat… 1.8 1999 4 manual… 4 18 26 p comp… 9 audi a4 quat… 1.8 1999 4 auto(l… 4 16 25 p comp… 10 audi a4 quat… 2 2008 4 manual… 4 20 28 p comp… # … with 224 more rows
Interactive elements can enable further exploration, give your charts more depth.
library('plotly')
Attaching package: ‘plotly’ The following object is masked from ‘package:ggplot2’: last_plot The following object is masked from ‘package:stats’: filter The following object is masked from ‘package:graphics’: layout
# need to run twice?
pp = ggplotly(p) %>% as_widget()
pp
Use "dummy" mappings to add data to the tooltip.
options(repr.plot.width = 5, repr.plot.height = 3)
p = ggplot(mpg, aes(x = displ, y = cty, color = class,
some_dummy_mapping = trans))
p = p + geom_point()
pp = ggplotly(p) %>% as_widget()
pp
Use tooltip
argument to ggplotly to select tooltip values.
options(repr.plot.width = 5, repr.plot.height = 3)
p = ggplot(mpg, aes(x = displ, y = cty, color = class,
some_dummy_mapping = trans))
p = p + geom_point()
pp = ggplotly(p, tooltip = c("trans")) %>% as_widget()
pp
# from https://plot.ly/ggplot2/animations/
df = data.frame(
x = c(1,2,3,4),
y = c(1,2,3,4),
f = c(1,2,3,4)
)
p = ggplot(df, aes(x, y))
p = p + geom_point(aes(frame = f))
pp = ggplotly(p, width = 600, height = 500) %>% as_widget()
pp
Warning message: “Ignoring unknown aesthetics: frame”
library('gapminder')
# also from https://plot.ly/ggplot2/animations/
p = ggplot(gapminder, aes(x = gdpPercap, y = lifeExp, color = continent))
p = p + geom_point(aes(size = pop, frame = year, ids = country))
p = p + scale_x_log10()
pp = ggplotly(p, height = 500) %>% as_widget()
pp
Warning message: “Ignoring unknown aesthetics: frame, ids”