隐藏所有系列highcharter-R选项

y0u0uwnf  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(108)

我有一个使用highcharter的图表:

library(highcharter)

year <- c(2017, 2018, 2019, 2020, 2021)
black <- c(12, 15, 23, 16, 11)
asian <- c(3, 12, 63, 46, 21)
white <- c(5, 45, 44, 44, 4)
hispanic <- c(23, 25, 44, 16, 112)

df <- data.frame(year, black, asian, white, hispanic)

highchart() %>% 
    hc_chart(type = "column") %>%
    hc_xAxis(categories = df$year) %>%
    hc_add_series(name="White",data = df$white) %>%
    hc_add_series(name="Black",data = df$black) %>%
    hc_add_series(name="Asian",data = df$asian) %>%
    hc_add_series(name="Hispanic",data = df$hispanic)

字符串
如果我单击图例中的一个系列,它会隐藏它:


的数据
有没有一种方法可以有一个按钮或东西,切换所有系列的开关(iidoEe。点击按钮隐藏所有系列)?例如,如果系列中有许多项目,则很难打开和关闭每个项目。

更新

我已经尝试了下面建议的解决方案,虽然我可以让它在rMarkdown文档中工作,但当我连接到HTML文档时,按钮失败并显示错误“任务必须是一个函数”:



当我追溯错误时,在检查HTML页面时,在“sources”选项卡下,我看到:

function evalAndRun(tasks, target, args) {
                    if (tasks) {
                        forEach(tasks, function(task) {
                            var theseArgs = args;
                            if (typeof (task) === "object") {
                                theseArgs = theseArgs.concat([task.data]);
                                task = task.code;
                            }
                            var taskFunc = tryEval(task);
                            if (typeof (taskFunc) !== "function") {
                                throw new Error("Task must be a function! Source:\n" + task);
                            }
                            taskFunc.apply(target, theseArgs);
                        });
                    }
                }


所以出于某种原因,它没有将toggleSeries函数识别为函数?

zour9fqk

zour9fqk1#

library(highcharter)
library(htmlwidgets)

year <- c(2017, 2018, 2019, 2020, 2021)
black <- c(12, 15, 23, 16, 11)
asian <- c(3, 12, 63, 46, 21)
white <- c(5, 45, 44, 44, 4)
hispanic <- c(23, 25, 44, 16, 112)

df <- data.frame(year, black, asian, white, hispanic)

js_code <- "
function toggleSeries() {
  var chart = Highcharts.charts[0];
  var series = chart.series;
  
  if (series[0].visible) {
    for (var i = 0; i < series.length; i++) {
      series[i].hide();
    }
  } else {
    for (var i = 0; i < series.length; i++) {
      series[i].show();
    }
  }
}

document.getElementById('toggleButton').addEventListener('click', toggleSeries);
"

hc <- highchart() %>% 
  hc_chart(type = "column") %>%
  hc_xAxis(categories = df$year) %>%
  hc_add_series(name = "White", data = df$white) %>%
  hc_add_series(name = "Black", data = df$black) %>%
  hc_add_series(name = "Asian", data = df$asian) %>%
  hc_add_series(name = "Hispanic", data = df$hispanic)

hc <- htmlwidgets::prependContent(hc, tags$button("Toggle All", id = "toggleButton"))

hc <- htmlwidgets::onRender(hc, js_code)

hc

字符串

相关问题