R语言 我只想在图表树图的图例中显示类别,有没有办法用shiny来实现?

wko9yo5t  于 2023-01-15  发布在  其他
关注(0)|答案(1)|浏览(119)

我想做一个树图来了解一个data.frame中的大小。让我给你看一个例子:

我使用下面的代码来生成这个图表:

library(shiny)
library(highcharter)
library(gapminder)
library(dplyr)

ui <- fluidPage(
  highchartOutput("hcontainer")
)
 

server <- function(input, output){
  output$hcontainer <- renderHighchart({  
    gapminder %>%
      filter(year  == 2007) %>% 
      data_to_hierarchical(group_vars = c(continent, country), 
                                        size_var = pop,
                                        colors = c('pink','yellow','blue','green','orange','red')) %>% 
      hchart(type = "treemap"
             #showInLegend = TRUE,
             #legendType='point',
             )  
  })
}

shinyApp(ui,
         server,
         options = list(launch.browser = TRUE)
         )

我看到可以通过取消注解hchart-函数中的这两行代码来创建图例,但结果不是我想要的:

有没有办法告诉highcharts我只想让大陆出现在我的传奇中?作为一个不太重要的旁注:highcharts中似乎有一个bug,因为在点击图例(您可以使用它隐藏/重新显示国家)后,它们会根据所在的大陆在图例中更改颜色:

kzmpq1sx

kzmpq1sx1#

使用下面的插件来实现这一点:

(function(H) {
  let pick = H.pick,
    defined = H.defined,
    fireEvent = H.fireEvent
  H.wrap(H.Legend.prototype.getAllItems = function(p) {
    var allItemsFirst = [],
      allItems = [];
    this.chart.series.forEach(function(series) {
      var seriesOptions = series && series.options;
      // Handle showInLegend. If the series is linked to another series,
      // defaults to false.
      if (series && pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? void 0 : false, true)) {
        // Use points or series for the legend item depending on
        // legendType
        allItemsFirst = allItems.concat(series.legendItems ||
          (seriesOptions.legendType === 'point' ?
            series.data :
            series));
      }
    });

    allItemsFirst.forEach(el => {
      if (el.isVisibleInLegend) {
        allItems.push(el)
      }
    })

    fireEvent(this, 'afterGetAllItems', {
      allItems: allItems
    });
    return allItems;
  });
}(Highcharts));

JS演示:https://jsfiddle.net/BlackLabel/vdqtok9m/
扩展高线图:https://www.highcharts.com/docs/extending-highcharts/extending-highcharts

相关问题