【问题标题】:Generate legends for each bubble in amcharts v4在 amcharts v4 中为每个气泡生成图例
【发布时间】:2019-02-26 12:57:19
【问题描述】:

我正在尝试使用 amCharts 第 4 版库创建气泡图。这里的每个气泡代表一个具有不同颜色的不同国家。现在我需要为图表中存在的每个气泡生成图例。我无法达到同样的效果。任何人都可以帮助我。

我正在使用下面提到的教程来创建气泡图。

https://www.amcharts.com/demos/zoomable-bubble-chart

【问题讨论】:

    标签: javascript charts amcharts


    【解决方案1】:

    根据official docs,您可以为您的图例使用自定义数据。

    chart.legend = new am4charts.Legend();
    chart.legend.data = [{
      "name": "2016",
      "fill":"#72A6B2"
    }, {
      "name": "2017",
      "fill": "#667E93"
    }, {
      "name": "2018",
      "fill": "#488BB2"
    }];
    

    要使其适应您的数据并为所有国家/地区创建图例,您可以使用以下 sn-p:

    chart.legend = new am4charts.Legend();
    chart.legend.data = chart.data.map(i => ({
      "name": i.title, 
      "fill": i.color
    }));
    

    要更新图例切换的数据,您可以在数据值上添加一个隐藏属性,并告诉 amcharts 使用它来隐藏一些项目符号。

    series.dataFields.hidden = "hidden";
    

    如果要在初始化时隐藏某些国家/地区,请将数据 id 添加到图例数据和 hidden 属性。

    chart.legend.data = chart.data.map(i => ({
      id: i.id, 
      name: i.title, 
      fill: i.color,
      visible: !i.hidden
    }));
    

    向图例添加点击事件以更新图表。使用"up" 事件,因为event.target.isActive"hit" 事件被调用后更新。

    chart.legend.itemContainers.template.events.on("up", (event) => {
      const id = event.target.dataItem.dataContext.id;
      chart.data.find(i => i.id === id).hidden = !event.target.isActive;
      chart.validateData();
    });
    

    我创建了this code pen 作为参考。

    【讨论】:

    • 我已经尝试过这段代码,这将为图表生成图例,但事件不适用于这些图例,例如单击国家/地区图例不会启用/禁用该特定国家/地区的气泡。
    • 感谢您的回复,我更新了我的答案和代码笔,并添加了一种可以解决您问题的方法。您可以使用 hidden 属性并在图例项状态更改时对其进行更新。希望它对你有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    相关资源
    最近更新 更多