繁体   English   中英

如何在 Apache Echarts 图表上标记一个点?

[英]How to mark a point on an Apache Echarts chart?

我有一个折线图,如何通过单击标记一个点并获取该点的值? 如果我 hover 将鼠标悬停在一个点上:

在此处输入图像描述

但是如何通过单击来标记点? 我希望标记留在那里并获得这一点的价值。

单击时显示工具提示

这实际上是由 Apache ECharts 支持的,只需更改图表选项即可。 您想将tooltip.triggerOn设置为'click'而不是'mousemove' 例如:

const options = {
  /* ... other options ... */
  tooltip: {
    show: true,
    trigger: "axis",
    triggerOn: "click",
  }
}

工具提示文档

访问值

您希望在单击/显示时从工具提示中获取值。 为此,我们使用事件并向showTip事件添加回调。

chart.on("showTip", console.log);

我没有做太多 Angular 所以这可能不是最好的代码,但它有效!

import { Component } from "@angular/core";
import { init, ECharts, EChartOption } from "echarts";

@Component({
  selector: "app-root",
  template: `
    <div id="echarts-container" #chartContainer>
      Content
    </div>
  `,
  // needs a minimum height
  styles: ["#echarts-container { height: 100vh; }"]
})
export class AppComponent {
  private chart?: ECharts;

  ngOnInit() {
    // I bet there is a more angular-specific way to access the element
    const chartContainer = document.getElementById("echarts-container");
    if (chartContainer instanceof HTMLDivElement) {
      this.initializeChart(chartContainer);
    } else {
      throw new Error("invalid element");
    }
  }

  ngOnDestroy() {
    this.chart?.dispose();
  }

  private doSomethingWithTooltipValue(value: number, label: string) {
    // we've got access -- now what do you want to do?
    console.log(`activated tooltip with label: ${label} and value: ${value}`);
  }

  private initializeChart(element: HTMLDivElement) {
    const option: EChartOption = {
      // some example data
      xAxis: {
        type: "category",
        data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
      },
      yAxis: {
        type: "value"
      },
      series: [
        {
          data: [150, 230, 224, 218, 135, 147, 260],
          type: "line"
        }
      ],
      // show the tooltip on click
      tooltip: {
        show: true,
        trigger: "axis",
        triggerOn: "click"
      }
    };
    const chart = init(element);
    chart.setOption(option);
    chart.resize();
    chart.on("showTip", ({ dataIndex, seriesIndex }) => {
      // TODO: would need to be more specific about the data types in order to lookup like this
      const label = option.xAxis.data[dataIndex];
      const value = option.series[seriesIndex].data[dataIndex];
      this.doSomethingWithTooltipValue(value, label);
    });

    // save chart instance to component so we can dispose of it in ngOnDestroy
    // there might be a more angular-specific way to do this
    this.chart = chart;
  }
}

代码沙盒链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM