以下是一个使用AmCharts4的示例,展示了如何进行数据分组,自定义工具提示文本和更改范围:
// 引入AmCharts库
import * as am4core from "@amcharts/amcharts4/core";
import * as am4charts from "@amcharts/amcharts4/charts";
import am4themes_animated from "@amcharts/amcharts4/themes/animated";
// 使用动画主题
am4core.useTheme(am4themes_animated);
// 创建图表实例
let chart = am4core.create("chartdiv", am4charts.XYChart);
// 设置数据
chart.data = [{
date: new Date(2021, 0, 1),
value: 100
}, {
date: new Date(2021, 0, 2),
value: 150
}, {
date: new Date(2021, 0, 3),
value: 200
}, {
date: new Date(2021, 0, 4),
value: 120
}, {
date: new Date(2021, 0, 5),
value: 180
}];
// 创建类目轴
let dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.grid.template.location = 0; // 网格线位置
// 创建值轴
let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
// 创建线图
let series = chart.series.push(new am4charts.LineSeries());
series.dataFields.valueY = "value";
series.dataFields.dateX = "date";
// 创建数据分组
let range = valueAxis.createSeriesRange(series);
range.value = 150; // 设置范围值
range.endValue = 200; // 设置结束范围值
range.contents.stroke = am4core.color("#FF0000"); // 设置范围颜色
range.contents.fill = am4core.color("#FF0000"); // 设置范围填充颜色
range.contents.strokeOpacity = 0.7; // 设置范围透明度
// 创建工具提示文本
series.tooltipText = "{valueY}";
// 设置图表的样式
chart.cursor = new am4charts.XYCursor();
chart.cursor.xAxis = dateAxis;
chart.cursor.snapToSeries = series;
// 将图表放入指定的元素中
chart.exporting.menu = new am4core.ExportMenu();
chart.exporting.menu.align = "right";
chart.exporting.menu.verticalAlign = "top";
chart.exporting.menu.items[0].icon = "/path/to/custom/icon.png";
chart.exporting.menu.items[0].iconPath = {
fill: "gray",
d:
"M16 15H3V4h9l4 4zm-1-2l3-3h-3V3H4v12h11v-3z"
};
// 更新图表尺寸
chart.events.on("ready", function () {
chart.exporting.getFormatOptions("pdf").pageOrientation = "landscape";
chart.exporting.getFormatOptions("pdf").marginRight = 40;
chart.exporting.getFormatOptions("pdf").marginLeft = 40;
chart.exporting.getFormatOptions("pdf").marginTop = 40;
chart.exporting.getFormatOptions("pdf").marginBottom = 40;
chart.exporting.getFormatOptions("pdf").filename = "chart";
});
// 更新图表
chart.invalidateData();
在上述代码中,我们首先引入了AmCharts库,并创建了一个图表实例。然后,我们设置了图表的数据,并创建了类目轴和值轴。接着,我们创建了一个线图系列,并使用createSeriesRange()方法创建了一个数据分组。我们还设置了工具提示文本和一些图表的样式。最后,我们将图表放置在一个指定的HTML元素中,并更新了图表的尺寸和数据。