Home > Software engineering >  Add average line/plot line to area highchart R
Add average line/plot line to area highchart R

Time:10-08

I know there are a few similar questions to this out there but they all seem to use javascript (?) or something besides the normal R coding so I don't know how to use it in my code... anyways all I want to do is add a plotline to my area chart that shows the average of the values, how do I do that? I know that highcharter itself can not calculate the average so I can do that myself but how do I create the plotline .... thank you so much. (i tried to make the code so that it is easily 'reproducible' ? hope it is ok). I attached a picture of the current chart if that helps. Here is my chart.

library(tidyverse)
library(highcharter) 
library(ggplot2)

data("diamonds", package = "ggplot2")

df <- diamonds %>%
  group_by(cut)%>%
  count()
head(df, 4)

# Create chart
hc <- df %>% 
  hchart(
    'area', hcaes(x = cut, y = n),
    color = "lightblue"
  ) %>%
hc_yAxis(title = list(text = "cut"))

# Display chart
hc

CodePudding user response:

Haha I got it. basically just this.

plotline <- list( color = "red", value = mean(diamonds$cut), width = 2, zIndex = 5 )

hc_yAxis(plotLines = list(plotline))

CodePudding user response:

Below is a mini example of using the highcharts widget. You can add each series using hc_add_series. In this case, we have two series and two y-axes. Using two y-axes helps to differentiate between the series. I'm not sure what values you're trying to calculate the average so I chose price.

Hope this helps add some clarity to highcharter!

library(tidyverse)
library(highcharter) 

df <- diamonds %>%
  group_by(cut)%>%
  summarise(
    n = n(),
    avg_price = round(mean(price),2)
  )

# create hc widget
highchart(type = "chart") %>%
  # add both series
  hc_add_series(df, hcaes(x = cut, y = n), color = "lightblue", yAxis = 0, type = "area", name = "N") %>%
  hc_add_series(df, hcaes(x = cut, y = avg_price), yAxis = 1, type = "line", name = "Avg Price") %>%
  # set type to categories since we're looking at categorical data
  hc_xAxis(type = "category", categories = df$cut) %>%
  hc_title(text = "Cut Freq vs Avg Price") %>%
  # add each y-axis which is linked above in 'hc_add_series'
  hc_yAxis_multiples(
    list(title = list(text = "Cut")), # yAxis = 0
    list(title = list(text = "Average Price"), opposite = TRUE) # yAxis = 1
  ) %>%
  hc_tooltip(shared = TRUE, split = FALSE)

Ex:

enter image description here

  • Related