Masood Sadat
Masood Sadat

Reputation: 1337

Combine scatter and line charts with highcharter in R

I am new to highcharter package. I want to add a line (regression line) on a scatter chart. It seems simple enough but I cannot crack it. I can make them separately using hchart() but they do not merge.

library(broom)
library(dplyr)
library(highcharter)

lm.model <- augment(lm(mpg ~ wt, data = mtcars))

lm.model %>%
  hchart(type = "scatter", hcaes(x = wt, y = mpg))

lm.model %>%
  hchart(type = "line", hcaes(x = wt, y = .fitted)

I also tried using hc_add_series_scatter() but I do not find a similar function for line.

highchart() %>%
  hc_add_series_scatter(x = lm.model$wt, y = lm.model$mpg)

Is it even possible to combine two chart types?

Upvotes: 2

Views: 3211

Answers (1)

Stephan
Stephan

Reputation: 2236

try

highchart() %>%
  hc_add_series(lm.model, "scatter", hcaes(wt, mpg)) %>% 
  hc_add_series(lm.model, "line", hcaes(x = wt, y = .fitted))

output is

enter image description here

Upvotes: 7

Related Questions