用react框架g2plot2.4.7版本 dualaxes slider的交互,例子
时间: 2023-07-04 18:24:01 浏览: 149
以下是使用React框架和g2plot 2.4.7版本实现DualAxes Slider交互的代码示例:
```jsx
import React, { useState, useEffect } from 'react';
import { Chart, Line, DualAxes } from '@antv/g2plot';
import '@antv/g2plot/dist/g2plot.css';
const MyChart = () => {
const [data, setData] = useState([
{ year: '1991', value: 3, count: 10 },
{ year: '1992', value: 4, count: 4 },
{ year: '1993', value: 3.5, count: 5 },
{ year: '1994', value: 5, count: 10 },
{ year: '1995', value: 4.9, count: 3 },
{ year: '1996', value: 6, count: 4 },
{ year: '1997', value: 7, count: 5 },
{ year: '1998', value: 9, count: 5 },
{ year: '1999', value: 13, count: 4 },
{ year: '2000', value: 15, count: 5 },
{ year: '2001', value: 16, count: 6 },
{ year: '2002', value: 18, count: 8 },
{ year: '2003', value: 21, count: 9 },
{ year: '2004', value: 22, count: 12 },
{ year: '2005', value: 24, count: 7 },
{ year: '2006', value: 26, count: 9 },
{ year: '2007', value: 28, count: 13 },
{ year: '2008', value: 30, count: 15 },
{ year: '2009', value: 31, count: 17 },
{ year: '2010', value: 32, count: 16 },
{ year: '2011', value: 33, count: 18 },
{ year: '2012', value: 34, count: 20 },
{ year: '2013', value: 35, count: 22 },
{ year: '2014', value: 36, count: 24 },
{ year: '2015', value: 37, count: 26 },
{ year: '2016', value: 38, count: 28 },
{ year: '2017', value: 39, count: 30 },
{ year: '2018', value: 40, count: 32 },
{ year: '2019', value: 41, count: 33 },
{ year: '2020', value: 42, count: 35 },
]);
const [chart, setChart] = useState(null);
useEffect(() => {
if (!chart) {
const plot = new Chart({
container: 'container',
autoFit: true,
height: 500,
padding: [40, 20, 40, 50],
});
plot.data(data);
plot.scale({
year: {
type: 'time',
mask: 'YYYY',
range: [0, 1],
},
value: {
min: 0,
max: 50,
nice: true,
},
count: {
min: 0,
max: 50,
nice: true,
},
});
plot.tooltip({
shared: true,
showMarkers: false,
});
const dualAxes = new DualAxes('dual', {
data,
xField: 'year',
yField: ['value', 'count'],
yAxis: [
{
min: 0,
max: 50,
nice: true,
},
{
min: 0,
max: 50,
nice: true,
},
],
meta: {
value: {
alias: 'Value',
},
count: {
alias: 'Count',
},
},
slider: {
start: 0.8,
end: 1,
},
});
plot.interaction('element-highlight-by-x');
plot.render();
setChart(plot);
}
}, [chart, data]);
return <div id="container" />;
};
export default MyChart;
```
在上面的代码中,我们使用了`useState`来存储数据和图表对象。当组件渲染时,我们初始化了一个`Chart`对象,并将数据绑定到该对象上。我们还使用`DualAxes`组件创建了一个双轴图表,并将其添加到刚创建的`Chart`对象上。我们还为双轴图表添加了一个滑块交互,该交互允许用户选择某个时间范围内的数据。最后,我们使用`render`方法将图表渲染到页面上。
在上述代码中,我们使用了`@antv/g2plot`的`Line`和`DualAxes`组件来创建图表。我们还使用了`interaction`方法添加了一个元素高亮交互,该交互可以让用户在鼠标悬停时高亮显示当前数据点。
阅读全文