Skip to content

ECharts Chart & Controllers API

Apache ECharts API —— 实例生命周期(init/setOption/resize)和驱动系列、轴和提示框的 option 对象。

2 classes · 9 methods

echarts.init

5 methods

通过 echarts.init(dom) 获取的 ECharts 图表上的实例方法。

new Chart(canvas, config)

在 DOM 元素上初始化 ECharts 实例,可选注册主题和渲染器/尺寸选项。

Parameters

NameTypeDescription
canvasHTMLCanvasElement | string | CanvasRenderingContext2DCanvas element, selector, or context.
configobject{ type, data, options }.

Returns

Chart

Example

chartjs
const chart = new Chart(document.getElementById('myChart'), {
  type: 'bar',
  data: { labels: ['A', 'B'], datasets: [{ data: [10, 20] }] },
  options: { responsive: true },
});
chart.config

设置(并合并)图表配置选项。使用 opts.notMerge=true 替换而非合并。

Returns

ChartConfiguration

Example

chartjs
chart.config.data.datasets[0].data = [30, 40];
chart.update();
chart.update(mode?)

返回图表的当前 option 对象(克隆),包括合并和默认值。

Parameters

NameTypeDescription
modestringOptional: 'none', 'reset', 'resize', 'show', 'hide', 'normal', 'active'.

Returns

void

Example

chartjs
chart.data.labels.push('C');
chart.data.datasets[0].data.push(30);
chart.update();
chart.destroy()

调整图表大小。无参数时适应容器;有参数时显式设置 width/height/silent。

Returns

void

Example

chartjs
chart.destroy();
chart.data = { labels, datasets }

销毁图表实例,释放资源并移除其创建的 DOM。

Returns

ChartData

Example

chartjs
chart.data = {
  labels: ['Jan', 'Feb', 'Mar'],
  datasets: [{
    label: 'Sales',
    data: [5, 10, 7],
    backgroundColor: '#36a2eb',
  }],
};

Option

4 methods

setOption 配置对象:series、xAxis、yAxis 和 tooltip 是每个图表的核心。

type: 'bar', datasets: [{ ...barOptions }]

系列定义数组。每个系列有 type(bar、line、pie、scatter 等)和 data 数组及类型特定选项。

Returns

config

Example

chartjs
new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Q1', 'Q2'],
    datasets: [{
      label: 'Revenue',
      data: [100, 200],
      backgroundColor: ['#36a2eb', '#ff6384'],
      borderWidth: 1,
    }],
  },
});
type: 'line', datasets: [{ ...lineOptions }]

配置 x 轴。type 'category' 使用数据标签;'value' 为数值;'time' 处理时间轴。

Returns

config

Example

chartjs
new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Mon', 'Tue', 'Wed'],
    datasets: [{
      label: 'Temp',
      data: [20, 24, 21],
      borderColor: '#36a2eb',
      fill: false,
      tension: 0.4,
    }],
  },
});
type: 'pie' | 'doughnut', datasets: [{ ...pieOptions }]

配置 y 轴。大多数图表使用一个值轴;多个轴可声明为数组。

Returns

config

Example

chartjs
new Chart(ctx, {
  type: 'doughnut',
  data: {
    labels: ['A', 'B', 'C'],
    datasets: [{
      data: [30, 40, 30],
      backgroundColor: ['#ff6384', '#36a2eb', '#cc65fe'],
    }],
  },
  options: { cutout: '50%' },
});
options.scales: { x, y }

配置悬停提示框。trigger 'item'(每个数据点,适合饼图)或 'axis'(每个轴,适合柱/折线图)。

Returns

config

Example

chartjs
options: {
  scales: {
    y: { beginAtZero: true, max: 250 },
    x: { grid: { display: false } },
  }
}