【问题标题】:How to add CLICK events on AMCHARTS 5 labels (x and y axis)?如何在 AMCHARTS 5 标签(x 和 y 轴)上添加 CLICK 事件?
【发布时间】:2023-01-27 05:22:33
【问题描述】:

我正在尝试为我的 AMCHARTS 5 标签添加基本的交互性。以此图表为例:

我需要能够单击图表左侧的名称。这实际上是 yAxis,因为我使用的是倒置图表。 在创建系列的函数中,我放置了这段代码:

series.columns.template.events.once("click", function(ev) {
                    console.log("Clicked on a column", ev.target);
                });

它使我的栏可以点击。我不知道如何参考左边的标签。

【问题讨论】:

  • 有解决办法吗?我也在找一样的

标签: amcharts5


【解决方案1】:

amCharts 5 中作为交互元素的标签很棘手。基本上,很难确定悬停/单击文本,因为不可能完全消除抗锯齿,而且实际的彩色区域非常小。

因此,如果我们需要工具提示具有交互性——有悬停工具提示或处理点击事件——我们需要为其添加背景。

背景不一定是可见的:我们可以设置它的fillOpacity: 0使其完全透明。

来源:Labels – amCharts 5 Documentation

在你的yAxis声明和初始化之后,你可以放这段代码:

yAxis.get("renderer").labels.template.setup = target => {
  target.setAll({
    cursorOverStyle: "pointer",
    background: am5.Rectangle.new(root, {
      fill: am5.color(0x000000),
      fillOpacity: 0
    })
  });
};
  
yAxis.get("renderer").labels.template.events.on("click", e => {
  console.log(e.target.dataItem.dataContext.category);
});

完整示例:

am5.ready(() => {

  let root = am5.Root.new("chartdiv");

  let chart = root.container.children.push(am5xy.XYChart.new(root, {}));

  let data = [{
    category: "Category 1",
    value: 10
  }, {
    category: "Category 2",
    value: 20
  }, {
    category: "Category 3",
    value: 15
  }];

  let yAxis = chart.yAxes.push(am5xy.CategoryAxis.new(root, {
    categoryField: "category",
    renderer: am5xy.AxisRendererY.new(root, {
      inversed: true,
      cellStartLocation: 0.1,
      cellEndLocation: 0.9
    })
  }));

  yAxis.data.setAll(data);
  
  yAxis.get("renderer").labels.template.setup = target => {
    target.setAll({
      cursorOverStyle: "pointer",
      background: am5.Rectangle.new(root, {
        fill: am5.color(0x000000),
        fillOpacity: 0
      })
    });
  };
  
  yAxis.get("renderer").labels.template.events.on("click", e => {
    console.log(e.target.dataItem.dataContext.category);
  });

  let xAxis = chart.xAxes.push(am5xy.ValueAxis.new(root, {
    min: 0,
    renderer: am5xy.AxisRendererX.new(root, {})
  }));

  let series = chart.series.push(am5xy.ColumnSeries.new(root, {
    name: "Series",
    xAxis: xAxis,
    yAxis: yAxis,
    valueXField: "value",
    categoryYField: "category"
  }));

  series.data.setAll(data);

});
#chartdiv {
  width: 100%;
  height: 350px;
}
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>

<div id="chartdiv"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 2020-09-14
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多