Reputation: 245
I'm trying to develop a part of a shiny app that makes an interactive visualization between a pie chart and a world map. So I want the users to click on the pie chart and then I can get the selected slice and the color code of the corresponding slice. I'm able to take the the slice that has been selected by the following code:
library(shiny)
library(highcharter)
ui <- fluidPage(
column(3,
highchartOutput("hcontainer",height = "300px")
),
column(3,
textOutput("clicked")
)
)
server <- function(input, output){
click_js <- JS("function(event) {Shiny.onInputChange('pieclick',event.point.name);}")
output$hcontainer <- renderHighchart({
highchart() %>%
hc_chart(type = "pie") %>%
hc_add_series(data = list(
list(y = 3, name = "cat 1"),
list(y = 4, name = "dog 11"),
list(y = 6, name = "cow 55"))) %>%
hc_plotOptions(series = list(events = list(click = click_js)))
})
output$clicked <- renderText({
input$pieclick
})
}
shinyApp(ui, server)
But I can't see any way on how I can get the corresponding color of the selected slice ?
A possible solution for that is if I can get a vector of all the slice and a vector of all the corresponding color-codes then I can make a comparison between the value I got from the selection and the colors of each value. I also couldn't find a way to get all the values and color-codes used automatically in the pei chart generation.
Upvotes: 1
Views: 200
Reputation: 29387
event.point
has loads of other data, one of which is the event.point.color
which we can take out. Do print out the object or event using console.log(event)
so you can see what other things you can use from the event...JS
, so going to do it on the R side...plotrix
package. May need to remove digits of some colors like: grey27
and so on, so will just gsub
and remove the digitslibrary(shiny)
library(plotrix)
library(highcharter)
ui <- fluidPage(
column(3,
highchartOutput("hcontainer",height = "300px")
),
column(3,
textOutput("clicked")
)
)
server <- function(input, output){
click_js <- JS("function(event) {Shiny.onInputChange('pieclick',[event.point.name,event.point.color]);}")
output$hcontainer <- renderHighchart({
highchart() %>%
hc_chart(type = "pie") %>%
hc_add_series(data = list(
list(y = 3, name = "cat 1"),
list(y = 4, name = "dog 11"),
list(y = 6, name = "cow 55"))) %>%
hc_plotOptions(series = list(events = list(click = click_js)))
})
output$clicked <- renderText({
req(input$pieclick)
d <- input$pieclick
mycolor <- gsub("[[:digit:]]", "", color.id(d[2])[1])
paste0(d[1],"-",mycolor)
})
}
shinyApp(ui, server)
Upvotes: 1