解决方案 Solution
VChart图表提供了对应的能力,支持通过配置scale来自由控制数据与值的映射关系。在双轴图图,控制颜色就可以使用scale来控制各个图形字段使用特定的颜色值。
更具体的配置规则,可参考:"https://visactor.io/vchart/option/barChart#scales.domain" (https://link.segmentfault.com/?enc=S8gcbuQ9AkheZBfX2GacqQ%3D%3D.HosGXUdWmtNPzqfx9dfECqaQNb61iqynoDKSawY5vlpgApHxc%2FidFT9JwsmIz4n7uyhp2FxMoyXP5fUAYBFohA%3D%3D)
代码示例 Code Example
import { useEffect, useRef } from "react";
import VChart from "@visactor/vchart";
export const Chart = () => {
const containerRef = useRef(null);
useEffect(() => {
const spec = {
type: "common",
data: [
{
id: "id0",
values: [
{ x: "Monday", type: "Breakfast", y: 15 },
{ x: "Monday", type: "Lunch", y: 25 },
{ x: "Tuesday", type: "Breakfast", y: 12 },
{ x: "Tuesday", type: "Lunch", y: 30 },
{ x: "Wednesday", type: "Breakfast", y: 15 },
{ x: "Wednesday", type: "Lunch", y: 24 },
{ x: "Thursday", type: "Breakfast", y: 10 },
{ x: "Thursday", type: "Lunch", y: 25 },
{ x: "Friday", type: "Breakfast", y: 13 },
{ x: "Friday", type: "Lunch", y: 20 },
{ x: "Saturday", type: "Breakfast", y: 10 },
{ x: "Saturday", type: "Lunch", y: 22 },
{ x: "Sunday", type: "Breakfast", y: 12 },
{ x: "Sunday", type: "Lunch", y: 19 }
]
},
{
id: "id1",
values: [
{ x: "Monday", type: "Beverage", y: 22 },
{ x: "Tuesday", type: "Beverage", y: 43 },
{ x: "Wednesday", type: "Beverage", y: 33 },
{ x: "Thursday", type: "Beverage", y: 22 },
{ x: "Friday", type: "Beverage", y: 10 },
{ x: "Saturday", type: "Beverage", y: 30 },
{ x: "Sunday", type: "Beverage", y: 50 }
]
}
],
color: {
type: "ordinal",
field: "type",
domain: ["Breakfast", "Lunch", "Beverage"],
range: ["lightPink", "lightBlue", "purple"]
},
series: [
{
type: "bar",
id: "bar",
dataIndex: 0,
label: { visible: true },
seriesField: "type",
xField: ["x", "type"],
yField: "y"
},
{
type: "line",
id: "line",
dataIndex: 1,
label: { visible: true },
seriesField: "type",
xField: "x",
yField: "y",
stack: false
}
],
axes: [
{ orient: "left", seriesIndex: [0] },
{ orient: "right", seriesId: ["line"], gird: { visible: false } },
{ orient: "bottom", label: { visible: true }, type: "band" }
],
legends: {
visible: true,
orient: "bottom"
}
};
const vchart = new VChart(spec, {
dom: containerRef.current
});
vchart.renderSync();
return () => vchart.release();
}, []);
return (
);
};
结果展示 Results
https://wmprod.oss-cn-shanghai.aliyuncs.com/images/20241216/69606f53a58eeded1870c1637fd1581a.png
在线示例:"https://codesandbox.io/s/color-scale-nh89qz?file=/src/App.js:..." (https://link.segmentfault.com/?enc=flfHebWkIcwEqD3dh1uxAg%3D%3D.S9E474KE75uPNOragRRxV3LqMITWyq9yyaWwsy1P8SICIuIYbgpWbYQpSlxrpRvIl9JM1EcX5t5xnOTtPvkUrCOS6weKvLX47U6%2FcT%2F9tYk%3D)
相关文档
"VChart
Github" (https://link.segmentfault.com/?enc=tIWVp%2BoEMA1NWTVJkLcngQ%3D%3D.MWcle6PyiAvz8DDMpIL5se8nXCBywHTCHDEsQYjU8WptsaZbMcXJRuQLUKh0RXkJ)
"VChart Scale
Guide" (https://link.segmentfault.com/?enc=vWc3ZDqTZxTTozu%2FkppFiQ%3D%3D.IB6qQhCHEcLYnCRmUauloJtsi193ZQizQ5XB6flRCkIHzJSiMwGGOcuonekJwTMdmcVsIblqAMNJyRV8VjIoYw%3D%3D)