JavaScript 可视化通常用于将数据以图形方式展示,以下是使用D3.js 和 Chart.js 这两种常用库进行可视化的案例。
案例一:使用 D3.js 实现条形图
1. 引入 D3.js
首先,需要在 HTML 中引入 D3.js:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>D3.js Bar Chart</title>
<script src="https://d3js.org/d3.v6.min.js"></script>
<style>
.bar {
fill: steelblue;
}
.bar:hover {
fill: orange;
}
.axis-label {
font-size: 14px;
}
</style>
</head>
<body>
<svg width="600" height="400"></svg>
<script>
// 数据
const data = [30, 80, 45, 60, 20, 90, 50];
// 设置 SVG 容器的宽高
const width = 600;
const height = 400;
// 选择 SVG 容器
const svg = d3.select("svg")
.attr("width", width)
.attr("height", height);
// 设置 X 和 Y 轴的比例尺
const xScale = d3.scaleBand()
.domain(data.map((d, i) => i))
.range([0, width])
.padding(0.1);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data)])
.range([height, 0]);
// 绘制条形图
svg.selectAll(".bar")
.data(data)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", (d, i) => xScale(i))
.attr("y", d => yScale(d))
.attr("width", xScale.bandwidth())
.attr("height", d => height - yScale(d));
// 添加 X 轴
svg.append("g")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(xScale).tickFormat(i => i + 1));
// 添加 Y 轴
svg.append("g")
.call(d3.axisLeft(yScale));
</script>
</body>
</html>
2. 代码说明:
使用 d3.select 选择 SVG 元素,并设置其宽高。
通过 d3.scaleBand() 和 d3.scaleLinear() 分别创建 X 和 Y 轴的比例尺,确定条形图的宽度和高度。
使用 svg.selectAll 选择并绘制条形图的矩形元素。
通过 d3.axisBottom 和 d3.axisLeft 创建并绘制 X 和 Y 轴。
3. 运行结果:
运行该代码后,你会看到一个简单的条形图,每个条形代表数据数组中的一个数值。
案例二:使用 Chart.js 实现折线图
1. 引入 Chart.js
首先,在 HTML 中引入 Chart.js:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chart.js Line Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div style="width:400px;height:200px">
<canvas id="myChart" width="400" height="200"></canvas>
</div>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
// 数据集
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Monthly Sales',
data: [65, 59, 80, 81, 56, 55, 40],
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 2,
fill: false,
tension: 0.1
}]
};
// 配置选项
const config = {
type: 'line',
data: data,
options: {
responsive: true,
scales: {
x: {
title: {
display: true,
text: 'Months'
}
},
y: {
beginAtZero: true,
title: {
display: true,
text: 'Sales (in USD)'
}
}
}
}
};
// 创建图表
const myChart = new Chart(ctx, config);
</script>
</body>
</html>
2. 代码说明:
使用 Chart 类创建图表,类型为 'line'(折线图)。
labels 定义 X 轴的月份标签,datasets 定义 Y 轴上的数值数据。
borderColor 设置折线颜色,tension 决定折线的弯曲度(0 为直线)。
options 对象中,scales 用于设置 X 和 Y 轴的属性。
3、效果
案例三:使用 D3.js 实现饼图
1. D3.js 饼图代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>D3.js Pie Chart</title>
<script src="https://d3js.org/d3.v6.min.js"></script>
<style>
.slice {
stroke: #fff;
}
</style>
</head>
<body>
<svg width="400" height="400"></svg>
<script>
// 设置数据
const data = [10, 20, 30, 40];
// 设置 SVG 尺寸
const width = 400;
const height = 400;
const radius = Math.min(width, height) / 2;
// 选择 SVG 容器
const svg = d3.select("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", `translate(${width / 2}, ${height / 2})`);
// 定义颜色比例尺
const color = d3.scaleOrdinal()
.domain(data)
.range(d3.schemeCategory10);
// 创建饼图布局
const pie = d3.pie();
// 创建弧生成器
const arc = d3.arc()
.innerRadius(0)
.outerRadius(radius);
// 将数据绑定到路径元素并绘制饼图
svg.selectAll('path')
.data(pie(data))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', d => color(d.data))
.attr('class', 'slice');
</script>
</body>
</html>
2. 代码说明:
d3.pie() 将数据转换为饼图所需的角度。
d3.arc() 定义了弧形的半径,用于绘制每个数据的切片。
d3.scaleOrdinal() 使用颜色比例尺来为不同的数据分段应用颜色。
使用 svg.selectAll('path') 绘制饼图切片。
3. 运行效果:
案例四:使用 Chart.js 实现柱状图
1. Chart.js 柱状图代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chart.js Bar Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<canvas id="barChart" width="400" height="200"></canvas>
<script>
const ctx = document.getElementById('barChart').getContext('2d');
// 数据集
const data = {
labels: ['Q1', 'Q2', 'Q3', 'Q4'],
datasets: [{
label: 'Sales in USD',
data: [12000, 15000, 8000, 18000],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)'
],
borderWidth: 1
}]
};
// 配置选项
const config = {
type: 'bar',
data: data,
options: {
scales: {
y: {
beginAtZero: true
}
}
}
};
// 创建图表
const barChart = new Chart(ctx, config);
</script>
</body>
</html>
2. 代码说明:
这里创建的是一个简单的柱状图,每个季度的销售额用不同颜色的柱状表示。
backgroundColor 和 borderColor 定义了柱状图每个柱体的颜色。
options 中定义了 Y 轴从零开始显示。
3. 运行效果:
案例五:使用 D3.js 实现散点图
1. D3.js 散点图代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>D3.js Scatter Plot</title>
<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<svg width="600" height="400"></svg>
<script>
// 数据
const data = [
{x: 30, y: 20},
{x: 50, y: 80},
{x: 90, y: 50},
{x: 120, y: 120},
{x: 150, y: 90},
{x: 200, y: 150}
];
// 设置 SVG 尺寸
const width = 600;
const height = 400;
// 选择 SVG 容器
const svg = d3.select("svg")
.attr("width", width)
.attr("height", height);
// 设置 X 和 Y 轴的比例尺
const xScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.x)])
.range([0, width]);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.y)])
.range([height, 0]);
// 绘制散点
svg.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", d => xScale(d.x))
.attr("cy", d => yScale(d.y))
.attr("r", 5)
.attr("fill", "steelblue");
// 添加 X 轴
svg.append("g")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(xScale));
// 添加 Y 轴
svg.append("g")
.call(d3.axisLeft(yScale));
</script>
</body>
</html>
2. 代码说明:
d3.scaleLinear() 用于将数据点映射到 SVG 坐标系中。
使用 svg.selectAll("circle") 绘制散点图中的每个点,并设置其 x 和 y 坐标。
3. 运行效果:
案例六:使用 Chart.js 实现饼图
1. Chart.js 饼图代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chart.js Pie Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<canvas id="pieChart" width="400" height="200"></canvas>
<script>
const ctx = document.getElementById('pieChart').getContext('2d');
// 数据集
const data = {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple'],
datasets: [{
label: 'Colors',
data: [12, 19, 3, 5, 2],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)'
],
borderWidth: 1
}]
};
// 配置选项
const config = {
type: 'pie',
data: data
};
// 创建图表
const pieChart = new Chart(ctx, config);
</script>
</body>
</html>
2. 代码说明:
创建一个简单的饼图,每个颜色表示不同的部分。
backgroundColor 设置了不同部分的颜色。