Madzia Madzia - 3 months ago 8
R Question

Setting variable column size in bar highchart (Rshiny)

I have a question relating to plot configuration in Rshiny. Basically, I have a bar chart and I would like to set the width for some columns and for the same X value.
Here is the simplified and reproductible example of the code:

library("shiny")
library("highcharter")

data(citytemp)

ui <- fluidPage(
h1("Highcharter EXAMPLE"),
fluidRow(
column(width = 8,
highchartOutput("hcontainer",height = "500px")
)
)
)

server <- function(input, output) {
data <- citytemp[,c("month","tokyo","new_york")]
output$hcontainer <- renderHighchart({
chart <- highchart() %>%
hc_chart(type = "bar") %>%
hc_title(text = "Monthly Average Temperature for TOKYO") %>%
hc_subtitle(text = "Source: WorldClimate.com") %>%
hc_xAxis(categories = c('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) %>%
hc_yAxis(title = list(text = "Temperature (C)"))

hc <- chart %>% hc_add_series(yAxis=0,name="Tokyo",data = data$tokyo)%>%
hc_plotOptions(bar = list(
pointWidth=10,
dataLabels = list(enabled = TRUE)
))

hc <- hc %>% hc_add_series(yAxis=0,name="NY",data = data$new_york)%>%
hc_plotOptions(bar = list(
pointWidth=0,
dataLabels = list(enabled = TRUE)
))

return(hc)
})
}

shinyApp(ui = ui, server = server)


I investigated and a simple way to do this is to change the hc_plotOptions. However, when I change the pointWidth for one series, it is applied to both. Is there a way to apply the wanted width only to one series ? Thank you very much for your help !
Best, Madzia

Answer

You need to add the pointWidth within the series itself when you are adding it. e.g. hc_add_series(pointWidth=10,...

rm(list = ls())
library("shiny")
library("highcharter")

data(citytemp)

ui <- fluidPage(
  h1("Highcharter EXAMPLE"),
  fluidRow(
    column(width = 8,highchartOutput("hcontainer",height = "500px")
    )
  )
)

server <- function(input, output) {
  data <- citytemp[,c("month","tokyo","new_york")]
  output$hcontainer <- renderHighchart({
    chart <-  highchart() %>% 
      hc_chart(type = "bar") %>% 
      hc_title(text = "Monthly Average Temperature for TOKYO") %>% 
      hc_subtitle(text = "Source: WorldClimate.com") %>% 
      hc_xAxis(categories = c('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                              'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) %>% 
      hc_yAxis(title = list(text = "Temperature (C)"))

    hc <- chart %>% hc_add_series(pointWidth=10,yAxis=0,name="Tokyo",data = data$tokyo)%>%
      hc_plotOptions(bar = list(dataLabels = list(enabled = TRUE)))

    hc <- hc %>% hc_add_series(pointWidth=0,yAxis=0,name="NY",data = data$new_york)%>%
      hc_plotOptions(bar = list(dataLabels = list(enabled = TRUE)))

    return(hc)
  })
} 

shinyApp(ui = ui, server = server)

enter image description here