1.首先是组件的一个安装:
npm install @antv/g2plot --save
2.dom的准备
<template>
<div class="one" id="my-chart" ref="chartRef"></div>
</template>
<style scoped>
.one {
width: 500px;
height: 200px;
border: 1px solid red;
}
</style>
3.初始化图表,页面的引用(这个里是vue3写法,vue2或者React也可以参考,差别不大)
<script>
//(1.)引用组件
import { onMounted, ref, nextTick } from "vue";
import { Mix } from "@antv/g2plot";
export default {
setup() {
const chartRef = ref(null);
onMounted(async () => {
// // (2.)避免dom问题,可自己优化
await nextTick(); // 等待下一个DOM更新周期
const data = [
{
product_type: "办公用品",
sex: "男",
order_amt: 8,
product_sub_type: "橡皮擦",
},
{
product_type: "办公用品",
sex: "男",
order_amt: 10,
product_sub_type: "书架",
},
{
product_type: "办公用品",
sex: "女",
order_amt: 21,
product_sub_type: "橡皮擦",
},
{
product_type: "办公用品",
sex: "女",
order_amt: 21,
product_sub_type: "书架",
},
{
product_type: "家电家具",
sex: "男",
order_amt: 13,
product_sub_type: "洗衣机",
},
{
product_type: "家电家具",
sex: "女",
order_amt: 2,
product_sub_type: "洗衣机",
},
{
product_type: "家电家具",
sex: "男",
order_amt: 5,
product_sub_type: "微波炉",
},
{
product_type: "家电家具",
sex: "女",
order_amt: 23,
product_sub_type: "微波炉",
},
{
product_type: "电子产品",
sex: "男",
order_amt: 33,
product_sub_type: "电脑",
},
{
product_type: "电子产品",
sex: "女",
order_amt: 4,
product_sub_type: "电脑",
},
{
product_type: "电子产品",
sex: "女",
order_amt: 23,
product_sub_type: "switch",
},
{
product_type: "电子产品",
sex: "男",
order_amt: 20.9,
product_sub_type: "switch",
},
];
const plot = new Mix(chartRef.value, {
appendPadding: 8,
tooltip: { shared: true },
syncViewPadding: true,
plots: [
// (1.)柱状图配置
{
type: "column",
options: {
data,
xField: "product_type",
yField: "order_amt",
isGroup: true,
isStack: true,
seriesField: "product_sub_type",
groupField: "sex",
columnWidthRatio: 0.3, // 设置柱状图的宽度为分组区域的60%
marginRatio: 0.5, // 设置两个柱子之间的间距,可以根据需要调整
tooltip: {
formatter: (datum) => ({
name: `${datum.product_sub_type} ${
datum.sex === "男" ? "👦" : "👧"
}`,
value: datum.order_amt,
}),
},
// 设置柱状图的颜色
color: ({ product_sub_type }) => {
if (
product_sub_type === "橡皮擦" ||
product_sub_type === "洗衣机" ||
product_sub_type === "电脑"
) {
return "#4c81ae";
} else if (
product_sub_type === "书架" ||
product_sub_type === "微波炉" ||
product_sub_type === "switch"
) {
return "#80b5c5";
} // 继续添加其他产品子类型的颜色映射
},
},
},
// (1.)折线图配置
{
type: "line",
options: {
data: [
{ xCategory: "A", value: 30 },
{ xCategory: "B", value: 35 },
{ xCategory: "C", value: 38 },
{ xCategory: "D", value: 42 },
{ xCategory: "E", value: 50 },
],
xField: "xCategory",
yField: "value",
xAxis: false,
yAxis: false,
smooth: true,
color: "#62d9ab",
lineStyle: {
lineWidth: 4, // 设置折线的粗细,单位为像素
},
point: {
size: 3, // 设置节点的大小
shape: "circle", // 设置节点的形状为圆形
style: {
fill: "#fff", // 设置节点的填充颜色
stroke: "#62d9ab", // 设置节点的边框颜色
lineWidth: 2, // 设置节点的边框宽度
},
},
},
},
],
});
plot.render();
});
return { chartRef };
},
};
</script>