How to add Highchart Bar lines and lables? - r

i would like to build an interactive chart but i'm very new in highcharts, i want to add average line for the data and change the labels of the bars, now per default say "Series 1:" i want to write "Cdays: ", this is my code now
# Load required R packages
library(highcharter)
# Set highcharter options
options(highcharter.theme = hc_theme_smpl(tooltip = list(valueDecimals = 2)))
df <- data.frame(Year=c('2015','2016','2017','2018','2019'),
CD=c(24, 18, 12, 9, 14))
head(df)
hc <- df %>%
hchart('column',
hcaes(x = Year, y = CD),
color = "#702080", borderColor = "#702080",
pointWidth = 80) %>%
hc_title(text = "Critical Days") %>%
hc_xAxis(categories = 'Critical Days') %>%
hc
Thanks !!

To add the mean line, try using plotLines in hc_yAxis and set the value to mean(df$CD). You can also adjust the color, add a label, etc. here.
To change the "Series 1" you see when hovering over the bars, you should set the name inside of hchart - in this case, "Cdays".
Other minor changes below - including use of df$Year for x-axis text labels.
df %>%
hchart('column',
hcaes(x = Year, y = CD),
color = "#702080",
borderColor = "#702080",
pointWidth = 80,
name = "Cdays") %>%
hc_title(text = "Critical Days") %>%
hc_xAxis(categories = df$Year) %>%
hc_yAxis(
title = list(text = "Cdays"),
plotLines = list(
list(
value = mean(df$CD),
color = "#00FF00",
width = 3,
zIndex = 4,
label = list(
text = "mean",
style = list(color = "#00FF00")
)
)
)
)

Related

echarts4r: e_mark_line symbol and name

How can I change the label of the line generated with e_mark_line? Here is my attempt, instead of showing the number 200, I'd like it to have my own label.
library(echarts4r)
library(tidyverse)
line <- list(
xAxis = 200
, name = "label 1"
)
USArrests %>%
e_charts(Assault) %>%
e_scatter(Murder, Rape) %>%
e_mark_line(data = line, symbol = "none", name = "label 2")
The underlying echarts JavaScript to mark lines, points and areas is rather convoluted. The title must be specified in the data. In the dev version there are convenience title related arguments.
library(echarts4r)
cars %>%
e_charts(speed) %>%
e_scatter(dist, symbol_size = 5) %>%
e_legend(FALSE) %>%
# manual
e_mark_line(data = list(xAxis = 7, symbol = "rect", label = list(formatter = "tortoise"))) %>%
# convenience arguments in latest github version
e_mark_line(data = list(xAxis = 12), title = "Speed Limit") %>%
e_mark_line(data = list(xAxis = 22), title = "Need for Speed")

R Highcharter: tooltip customization

I created a chart using highcharter in a shiny dashboard and I am trying to customize the tooltip. The chart is combined line and scatter plot. I would like it to do the following:
1) Have a single box for hover information (it currently has one for the line and one for scatter)
2) Be able to use different column of information that is not used in the series x or y values
I would like the tooltip to display the following information (whether I hover over the scatter point or line) for each particular x-axis value.
Overall
Mean: 2 [Mean: data$avghours]
Dog: 1 [data$animal: data$hours]
Below is the example code I've written that demonstrates my problem:
library (shiny)
library (shinydashboard)
library (highcharter)
header <- dashboardHeader(title = "Example")
body <- dashboardBody(
fluidRow(
box(title = "example", status = "primary", solidHeader = TRUE,
highchartOutput("chart")
)
)
)
sidebar <- dashboardSidebar()
ui <- dashboardPage(header, sidebar, body)
server <- function(input, output) {
date <- c(1,2,3,4,5,6,7,8,9,10)
hours <- c(1,5,4,1,6,5,7,5,4,3)
avghours <- c(2,2,2,3,3,3,2,2,2,2)
animal <- c("dog","cat","cat","cat","cat","cat","cat","cat","dog","dog")
data <- data.frame(date,hours,avghours,animal)
output$chart <- renderHighchart({
highchart() %>%
hc_add_series(name = "Shipments", data=data$hours, type = "scatter", color = "#2670FF", marker = list(radius = 2), alpha = 0.5) %>%
hc_add_series(name = "Rolling Mean", data=data$avghours, color = "#FF7900") %>%
hc_yAxis(min = 0, title = list(text = "Hours")) %>%
hc_tooltip(crosshairs = TRUE)
})
}
shinyApp(ui, server)
Firt of all, you need to add all the data instead give only the vector (the vector DON´T have all the information to the tooltip you want).
To do this you need change the data argument using the data.frame with the hcaes helper function in the mapping argument to define which variable use in every axis:
highchart() %>%
hc_add_series(data = data, mapping = hcaes(x=date, y=hours), name = "Shipments", type = "scatter", color = "#2670FF", marker = list(radius = 2), alpha = 0.5) %>%
hc_add_series(data = data, hcaes(date, avghours), name = "Rolling Mean", type = "line", color = "#FF7900") %>%
hc_yAxis(min = 0, title = list(text = "Hours")) %>%
hc_tooltip(crosshairs = TRUE)
Then you can use the tooltip argument in every hc_add_series to define the tooltip in each series:
highchart() %>%
hc_add_series(data = data, hcaes(date, hours), name = "Shipments", type = "scatter",
tooltip = list(pointFormat = "tooltip with 2 values {point.animal}: {point.hours}")) %>%
hc_add_series(data = data, hcaes(date, avghours), name = "Rolling Mean", type = "line",
tooltip = list(pointFormat = "Avg hour text! {point.avghours}")) %>%
hc_yAxis(min = 0, title = list(text = "Hours")) %>%
hc_tooltip(crosshairs = TRUE)

R Shiny Highcharter - How to use hc_rangeSelector()

I'm plotting a financial intra-day time serie on an R-Shiny project using the highcharter package. I'm using the following code for the server part in order to get the output (note that xtsPrices() is a function that returns an xts intraday time-serie):
output$plot <- renderHighchart({
y <- xtsPrices()
highchart() %>%
hc_exporting(enabled = TRUE)%>%
hc_add_series_ohlc(y) %>%
hc_add_theme(hc_theme_538(colors = c("red", "blue", "green"),
chart = list(backgroundColor = "white") ))
})
I read in the documentation that in order to personalize zoom buttons I have to deal with the hc_rangeSelector() function, but I don't understand how to specify them in this R-Shiny environment as shown for the javascript case in Highstock API. In particular - because it's an intra-day time-serie - I would need buttons like "20min", "1h", "3h", "1D", etc.
For intra-day data you can do something like this:
hc <- highchart() %>%
hc_exporting(enabled = TRUE) %>%
hc_add_series_ohlc(y, yAxis = 0, name = "Sample Data", id = "T1",smoothed=TRUE,forced=TRUE,groupPixelWidth=24) %>%
hc_rangeSelector( buttons = list(
list(type = 'all', text = 'All'),
list(type = 'hour', count = 2, text = '2h'),
list(type = 'hour', count = 1, text = '1h'),
list(type = 'minute', count = 30, text = '30m'),
list(type = 'minute', count = 10, text = '10m'),
list(type = 'minute', count = 5, text = '5m')
)) %>%
hc_add_theme(hc_theme_538(colors = c("red", "blue", "green"),chart = list(backgroundColor = "white") ))
hc

Highchart shiny R scatter plot - how to define individual point colors

I'm trying to create a scatter plot in highcharts shiny R but I need to give a different color to points, individually. Consider for instance the following example:
library("MASS")
dscars <- round(mvrnorm(n = 20, mu = c(1, 1), Sigma = matrix(c(1,0,0,1),2)), 2)
highchart() %>%
hc_chart(type = "scatter", zoomType = "xy") %>%
hc_tooltip(
useHTML = TRUE,
pointFormat = paste0("<span style=\"color:{series.color};\">{series.options.icon}</span>",
"{series.name}: <b>[{point.x}, {point.y}]</b><br/>")
) %>%
hc_add_series(data = list.parse2(as.data.frame(dscars)),
marker = list(symbol = fa_icon_mark("car")),
icon = fa_icon("car"), name = "car")
My objective is to give to this 20 points, an unique color.
I tried to set the "fillColor" inside marker list as also as to define the color of the series, both with a vector of 20 colors but I had no success.
Can any one give me a hint?
Thank you
In highcharts (the highcharter) the point can be given as other parameter, same as x and y. So first
library("MASS")
dscars <- round(mvrnorm(n = 20, mu = c(1, 1), Sigma = matrix(c(1,0,0,1),2)), 2)
dscars <- as.data.frame(dscars)
names(dscars) <- c("x", "y") # it's better give a named list IMHO
dscars$color <- colorize(1:nrow(dscars))
colorizeis a function to create a color vector given other vector. In this case the input vector is a sequence (no repeated) so the output will be differents colors. But if you want yo can use your own colors.
highchart() %>%
hc_chart(type = "scatter", zoomType = "xy") %>%
hc_tooltip(
useHTML = TRUE,
pointFormat = paste0("<span style=\"color:{point.color};\">{series.options.icon}</span>",
"{series.name}: <b>[{point.x}, {point.y}]</b><br/>")
) %>%
hc_add_series(data = list_parse(dscars),
marker = list(symbol = fa_icon_mark("car")),
icon = fa_icon("car"), name = "car")
Note we used:
color:{point.color}; in the poinFormat, beacuse every point has its own color in the color accesor.
I used list_parse which parse the data frame in a named list instead of unnamed list so highcharts understand how to use the data. list_parse is the same list.parse3 for old version of highcharts.
Hope it helps.
Is this what you want?
rm(list = ls())
library(highcharter)
library(MASS)
dscars <- data.frame(round(mvrnorm(n = 20, mu = c(1, 1), Sigma = matrix(c(1,0,0,1),2)), 2))
highchart() %>%
hc_chart(type = "scatter", zoomType = "xy") %>%
hc_tooltip(
useHTML = TRUE,
pointFormat = paste0("<span style=\"color:{colorByPoint:true};\">{series.options.icon}</span>",
"{series.name}: <b>[{point.x}, {point.y}]</b><br/>")
) %>%
hc_add_series(data = list.parse2(as.data.frame(dscars)),colorByPoint = TRUE,
marker = list(symbol = fa_icon_mark("car")),
icon = fa_icon("car"), name = "car")

add vertical and horizontal lines in hplot (rcharts)

I'm trying to add horizontal and vertical lines in a highchart (rcharts) in a revealjs presentation.
I tried to modify the code of this post in this way:
require(xlsx)
library(rCharts)
Perhplot.df <-read.xlsx("C:\\RDirectory\\AREALAVORO\\JOB\\RISULTATI2.xlsx", sheetName="completo2")
lDf <- split(Perhplot.df, Perhplot.df$variable)
h16 <- hPlot(protection ~ days, data = lDf$Exposure,
type = "bubble",
group = "label",
title = "By Days of Exposure",
subtitle = "Move the mouse pointer on the bubbles to view the data",
size = "cluster_size",
group = "label")
h16$set(width = 1000, height = 600)
ord <- c("Less than 1 week"=0,
"1-2 weeks"=1,
"3-4 weeks"=2,
"More than 4 weeks"=3,
"Mean"=4
)
h16$params$series <- lapply(h16$params$series, function(d){
temp = ord[d$name]
names(temp) = NULL
d$legendIndex = temp
return(d)
})
h16$yAxis(min = 35, max = 70, title = list(text = "Level of Protection"))
h16$xAxis(min = 0, max = 45, title = list(text = "Days of Exposure"))
dfy<-data.frame(y=c(35,58,70), x=c(18.8,18.8,18.8))
h16$layer(y~x,data=dfy,type="line",color=list(const = 'darkblue'))
h16$show('inline', include_assets = TRUE)
the bubble plot is ok but then I try to add the vertical line I have this error:
Error in envRefInferField(x, what, getClass(class(x)), selfEnv) : ‘layer’ is not a valid field or method name for reference class “Highcharts”
So the solution works for Dimple Charts but not for Highcharts...
As same as rcharts highcharts plotLines.
You need to use plotLines argument:
library("rCharts")
# Some data
x <- abs(rnorm(10))
# A graph with column
h <- Highcharts$new()
h$chart(type = "column")
h$series(data = x)
h$xAxis(categories = letters[1:10])
# the horizontal line
h$yAxis(title = list(text = "rnorm()"),
plotLines = list(list(
value = mean(x),
color = '#ff0000',
width = 3,
zIndex = 4,
label = list(text = "mean",
style = list( color = '#ff0000', fontWeight = 'bold' )
))))
h
Yo add vertical you change yAxis by xAxis.
Or if you use highcharter (It's a new wrapper of highcharts for R):
h2 <- highchart() %>%
hc_chart(type = "column") %>%
hc_add_serie(data = x) %>%
hc_xAxis(categories = letters[1:10]) %>%
hc_yAxis(title = list(text = "rnorm()"),
plotLines = list(list(
value = mean(x),
color = '#ff0000',
width = 3,
zIndex = 4,
label = list(text = "mean",
style = list( color = '#ff0000', fontWeight = 'bold' )
))))
h2
Source: http://jkunst.com/highcharter/highcharts-api.html#hc_xaxis-and-hc_yaxis

Resources