Highcharter R Package Essentials for Easy Interactive Graphs

Highchart Interactive Scatter Plot in R

This article describes how to create an interactive scatter plot in R using the highchart R package.



Contents:

Loading required R packages

library(highcharter) 

Data preparation

Demo dataset: mtcars. The variable cyl is used as grouping variable.

# Load data
data("mtcars")
df <- mtcars
# Convert cyl as a grouping variable
df$cyl <- as.factor(df$cyl)
# Inspect the data
head(df[, c("wt", "mpg", "cyl", "qsec")], 4)
##                  wt  mpg cyl qsec
## Mazda RX4      2.62 21.0   6 16.5
## Mazda RX4 Wag  2.88 21.0   6 17.0
## Datsun 710     2.32 22.8   4 18.6
## Hornet 4 Drive 3.21 21.4   6 19.4

Basic scatter plots

hc <- df %>% hchart('scatter', hcaes(x = wt, y = mpg))
hc

Scatter plots with multiple groups

# Change color by groups
# Set custom colors
hc <- df %>% 
  hchart('scatter', hcaes(x = wt, y = mpg, group = cyl)) %>%
  hc_colors(c("#00AFBB", "#E7B800", "#FC4E07"))
hc

Add regression lines

# Fit regression model
library(dplyr)
library(broom)
model <- lm(mpg ~ wt, data = df)
fit <- augment(model) %>% arrange(wt)

# Visualization
hc <- df %>% 
  hchart('scatter', hcaes(x = wt, y = mpg, group = cyl)) %>%
  hc_add_series(
    fit, type = "line", hcaes(x = wt, y = .fitted),
    name = "Fit", id = "fit"
    ) 
hc

Bubble chart

In a bubble chart, points size is controlled by a continuous variable, here qsec.

hc <- df %>% 
  hchart(
    'scatter', hcaes(x = wt, y = mpg, size = qsec, group = cyl),
    maxSize = "10%"
    )
hc

Color by a continuous variable

hc <- df %>% 
  hchart('scatter', hcaes(x = wt, y = mpg, color = mpg))
hc



Version: Français

(Next Lesson) Highchart Interactive Boxplot in R
Back to Highcharter R Package Essentials for Easy Interactive Graphs

No Comments

Give a comment

Want to post an issue with R? If yes, please make sure you have read this: How to Include Reproducible R Script Examples in Datanovia Comments