0
votes

I need to add a legend to a piechart using any highcharts package for R on a shiny app(highcharter, rcharts, whatever).

Ex. Code

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

data(citytemp)

ui <- fluidPage(
  h1("Highcharter Demo"),
  fluidRow(
    column(width = 4, class = "panel",
           selectInput("type", label = "Type", width = "100%",
                       choices = c("line", "column", "bar", "spline")), 
           selectInput("stacked", label = "Stacked",  width = "100%",
                       choices = c(FALSE, "normal", "percent")),
           selectInput("theme", label = "Theme",  width = "100%",
                       choices = c(FALSE, "fivethirtyeight", "economist",
                                   "darkunica", "gridlight", "sandsignika",
                                   "null", "handdrwran", "chalk")
           )
    ),
    column(width = 8,
           highchartOutput("hcontainer",height = "500px")
    )
  )
)

server = function(input, output) {
  
  output$hcontainer <- renderHighchart({
    
    hc <- hc_demo() %>%
      hc_rm_series("Berlin") %>% 
      hc_chart(type = 'pie')
    
    if (input$stacked != FALSE) {
      hc <- hc %>%
        hc_plotOptions(showInLegend=TRUE,dataLabels=FALSE)
    }
    hc
    
  })
  
}

shinyApp(ui = ui, server = server)

The code runs a crappy example of a pie chart, and no matter where I look I can't find an example of a highcharts pie chart with legends.

Attempts to fix it include:

hc_legend(enabled=TRUE) <-- does not work, makes no change.

hc_plotOptions(showInLegend=TRUE,dataLabels=FALSE) <-- Again, no change

Using Rcharts with similar attempts, they both failed, I then became hopelessly lost looking through source code for highcharts

Using similar functionality I was able to create highchart pie charts with legends in a typical JS format by using either of the two solutions above, does anybody have a reasonable solution to this problem? Possibly a link to a decent resource for figuring it out?

actual JS example of highcharts with legend, shamelessly ripped from offical highcharts website.

$(function () {

    $(document).ready(function () {

        // Build the chart
        $('#container').highcharts({
            chart: {
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false,
                type: 'pie'
            },
            title: {
                text: 'Browser market shares January, 2015 to May, 2015'
            },
            tooltip: {
                pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    showInLegend: true
                }
            },
            series: [{
                name: 'Brands',
                colorByPoint: true,
                data: [{
                    name: 'Microsoft Internet Explorer',
                    y: 56.33
                }, {
                    name: 'Chrome',
                    y: 24.03,
                    sliced: true,
                    selected: true
                }, {
                    name: 'Firefox',
                    y: 10.38
                }, {
                    name: 'Safari',
                    y: 4.77
                }, {
                    name: 'Opera',
                    y: 0.91
                }, {
                    name: 'Proprietary or Undetectable',
                    y: 0.2
                }]
            }]
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
1
You can try to prepare your own HTML legend, like here: jsfiddle.net/N3KAC/1Sebastian Bochan
@SebastianBochan I'll let you know how it goes. I might be able to incorporate that into R or shiny.Edge363
Sorry Im not familiar with the R gems etc ;)Sebastian Bochan

1 Answers

5
votes

First of all, in your example the hc_demo() is a line chart example, so it will not work well just by changing the type of the chart due to the data is not coded as required for a pie chart (y and name values).

Here are is a raw example. As you showed in the javascript example you just need to force to show the legend because for pie charts the default value is false. This is achieved using plotOptions -> pie -> showInLegend = TRUE.

library(highcharter)
highchart() %>% 
  hc_chart(type = "pie") %>% 
  hc_plotOptions(
    series = list(showInLegend = TRUE)
  ) %>% 
  hc_add_series(data = list(
    list(y = 3, name = "cat 1"),
    list(y = 4, name = "cat 2")
    )
  )

Finally I recommend you check replicating highcharts demos in highcharter.