d3.js 教程 模仿echarts折线图
今天我们来仿echarts折线图,这个图在echarts是折线图堆叠,但是我用d3改造成了普通的折线图,只为了大家学习(其实在简单的写一个布局就可以)。废话不多说商行代码。
1 制作 Line 类
class Line {
constructor() {
this._width = 1100;
this._height = 800;
this._padding = 10;
this._offset = 35;
this._margins = {right: 50,bottom: 50,left: 70,top: 100};
this._scaleX = d3.scaleBand().range([0, this.quadrantWidth()]).paddingInner(1).align(0);
this._scaleY = d3.scaleLinear().range([this.quadrantHeight(), 0]);
this._color = d3.scaleOrdinal(d3.schemeCategory10);
this._dataX = [];
this._series = [];
this._svg = null;
this._body = null;
this._tooltip = null;
this._transLine = null;
this._activeR = 5;
this._ticks = 5;
}
render() {
if(!this._tooltip) {
this._tooltip = d3.select('body')
.append('div')
.style('left', '40px')
.style('top', '30px')
.attr('class', 'tooltip')
.html('');
}
if(!this._svg) {
this._svg = d3.select('body')
.append('svg')
.attr('width', this._width)
.attr('height', this._height)
.style('background', '#f3f3f3')
this.renderAxes();
this.renderClipPath();
}
this.renderBody();
}
renderAxes() {
let axes = this._svg.append('g')
.attr('class', 'axes'); this.renderXAxis(axes);
this.renderYAxis(axes);
}
renderXAxis(axes) {
let xAxis = d3.axisBottom().scale(this._scaleX).ticks(this._dataX.length);
axes.append('g')
.attr('class', 'x axis')
.attr('transform', `translate(${this.xStart()}, ${this.yStart()})`)
.call(xAxis) d3.selectAll('g.x .tick text')
.data(this._dataX)
.enter()
}
renderYAxis(axes) {
let yAxis = d3.axisLeft().scale(this._scaleY).ticks(this._ticks);
axes.append('g')
.attr('class', 'y axis')
.attr('transform', `translate(${this.xStart()}, ${this.yEnd()})`)
.call(yAxis) d3.selectAll('.y .tick')
.append('line')
.attr('class', 'grid-line')
.attr('x1', 0)
.attr('y1', 0)
.attr('x2', this.quadrantWidth())
.attr('y2', 0)
}
renderClipPath() {
this._svg.append('defs')
.append('clipPath')
.attr('id', 'body-clip')
.append('rect')
.attr('x', 0 - this._activeR - 1)
.attr('y', 0)
.attr('width', this.quadrantWidth() + (this._activeR + 1) * 2)
.attr('height', this.quadrantHeight())
}
renderBody() {
if(!this._body) {
this._body = this._svg.append('g')
.attr('class', 'body')
.attr('transform', `translate(${this._margins.left},${this._margins.top})`)
.attr('clip-path', 'url(#body-clip)')
this.renderTransLine()
}
this.renderLines();
this.renderDots();
this.listenMousemove();
}
renderTransLine() {
this._transLine = this._body.append('line')
.attr('class', 'trans-line')
.attr('x1', 0)
.attr('y1', 0)
.attr('x2', 0)
.attr('y2', this._scaleY(0))
.attr('stroke-opacity', 0)
}
renderLines() {
let line = d3.line()
.x((d,i) => this._scaleX(this._dataX[i]))
.y(d => this._scaleY(d)) let lineElements = this._body
.selectAll('path.line')
.data(this._series); let lineEnter = lineElements
.enter()
.append('path')
.attr('class', 'line')
.attr('d', d => line(d.data.map(v => 0)))
.attr('stroke', (d,i) => this._color(i)) let lineUpdate = lineEnter
.merge(lineElements)
.transition()
.duration(100)
.ease(d3.easeCubicOut)
.attr('d', d => line(d.data)) let lineExit = lineElements
.exit()
.transition()
.attr('d', d => line(d.data))
.remove();
}
renderDots() {
this._series.forEach((d,i) => {
let dotElements = this._body
.selectAll('circle._' + i)
.data(d.data); let dotEnter = dotElements
.enter()
.append('circle')
.attr('class', (v, index) => 'dot _' + i + ' index_' + index)
.attr('cx', (d,i) => this._scaleX(this._dataX[i]))
.attr('cy', d => this._scaleY(d))
.attr('r', 1e-6)
.attr('stroke', (d,i) => this._color(i)) let dotUpdate = dotEnter
.merge(dotElements)
.transition()
.duration(100)
.ease(d3.easeCubicOut)
.attr('cx', (d,i) => this._scaleX(this._dataX[i]))
.attr('cy', d => this._scaleY(d))
.attr('r', 2) let dotExit = dotElements
.exit()
.transition()
.attr('r', 0)
.remove();
})
this._dataX.forEach((d,i) => {
d3.selectAll('circle._' + i)
.attr('stroke', this._color(i))
})
}
listenMousemove() {
this._svg.on('mousemove', () => {
let px = d3.event.offsetX;
let py = d3.event.offsetY;
if(px < this.xEnd() && px > this.xStart() && py < this.yStart() && py > this.yEnd()) {
this.renderTransLineAndTooltip(px, py, px - this.xStart());
} else {
this.hideTransLineAndTooltip();
}
})
}
renderTransLineAndTooltip(x, y, bodyX) {
//鼠标悬浮的index
let cutIndex = Math.floor((bodyX + this.everyWidth() / 2) / this.everyWidth());
//提示线位置
this._transLine.transition().duration(50).ease(d3.easeLinear).attr('x1', cutIndex * this.everyWidth()).attr('x2', cutIndex * this.everyWidth()).attr('stroke-opacity', 1);
// dot圆圈动画
d3.selectAll('circle.dot').transition().duration(100).ease(d3.easeCubicOut).attr('r', 2)
d3.selectAll('circle.index_' + cutIndex).transition().duration(100).ease(d3.easeBounceOut).attr('r', this._activeR)
//提示框位置和内容
if(x > this.quadrantWidth() - this._tooltip.style('width').slice(0,-2) - this._padding * 2) {
x = x - this._tooltip.style('width').slice(0,-2) - this._padding * 2 - this._offset * 2;
}
if(y > this.quadrantHeight() - this._tooltip.style('height').slice(0,-2) - this._padding * 2) {
y = y - this._tooltip.style('height').slice(0,-2) - this._padding * 2 - this._offset * 2;
}
let str = `<div style="text-align: center">${this._dataX[cutIndex]}</div>`;
this._series.forEach((d, i) => {
str = str + `<div style="width: 15px;height: 15px;vertical-align: middle;margin-right: 5px;border-radius: 50%;display: inline-block;background: ${this._color(i)};"></div>${d.name}<span style="display: inline-block;margin-left: 20px">${d['data'][cutIndex]}</span><br/>`
})
this._tooltip.html(str).transition().duration(100).ease(d3.easeLinear).style('display', 'inline-block').style('opacity', .6).style('left', `${x + this._offset + this._padding}px`).style('top', `${y + this._offset + this._padding}px`);
}
hideTransLineAndTooltip() {
this._transLine.transition().duration(50).ease(d3.easeLinear).attr('stroke-opacity', 0);
d3.selectAll('circle.dot').transition().duration(100).ease(d3.easeCubicOut).attr('r', 2);
this._tooltip.transition().duration(100).style('opacity', 0).on('end', function () {d3.select(this).style('display', 'none')});
}
everyWidth() {
return this.quadrantWidth() / (this._dataX.length - 1);
}
quadrantWidth() {
return this._width - this._margins.left - this._margins.right;
}
quadrantHeight() {
return this._height - this._margins.top - this._margins.bottom;
}
xStart() {
return this._margins.left;
}
xEnd() {
return this._width - this._margins.right;
}
yStart() {
return this._height - this._margins.bottom;
}
yEnd() {
return this._margins.top;
}
scaleX(a) {
this._scaleX = this._scaleX.domain(a);
}
scaleY(a) {
this._scaleY = this._scaleY.domain(a)
}
selectMaxYNumber(arr) {
let temp = [];
arr.forEach(item => temp.push(...item.data));
let max = d3.max(temp);
let base = Math.pow(10, Math.floor(max / 4).toString().length - 1);
//获取Y轴最大值
return Math.floor(max / 4 / base) * 5 * base;
}
dataX(data) {
if(!arguments.length) return this._dataX;
this._dataX = data;
this.scaleX(this._dataX);
return this;
}
series(series) {
if(!arguments.length) return this._series;
this._series = series;
let maxY = this.selectMaxYNumber(this._series);
this.scaleY([0, maxY])
return this;
}
}
2 css 文件
.domain {
stroke-width:;
fill: none;
stroke: #888;
shape-rendering: crispEdges;
}
.tick text {
font-size: 14px;
}
.grid-line {
fill: none;
stroke: #888;
opacity: .4;
shape-rendering: crispEdges;
}
.trans-line {
fill: none;
stroke: #666;
opacity: .4;
}
.line {
fill: none;
stroke-width:;
}
.dot {
fill: #fff;
}
.tooltip{
font-size: 15px;
width: auto;
padding: 10px;
height: auto;
position: absolute;
background-color: #000000;
opacity: .6;
border-radius:5px;
color: #ffffff;
display: none;
}
3 HTML 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>$Title$</title>
<link rel="stylesheet" type="text/css" href="css/base.css"/>
<script type="text/javascript" src="js/d3.v4.js"></script>
<script type="text/javascript" src="js/line.js"></script>
</head>
<body>
<script>
var dataX = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
var series = [{name: '邮件营销', data:[120, 132, 101, 134, 90, 230, 210]},
{name: '联盟广告', data:[340, 314, 292, 368, 380, 560, 520]},
{name: '视频广告', data:[490, 546, 493, 522, 570, 890, 930]},
{name: '直接访问', data:[810, 878, 794, 856, 960, 1220, 1250]},
{name: '搜索引擎', data:[1640, 1864, 1802, 1868, 2580, 2660, 2640]}]
var line = new Line();
line
.dataX(dataX)
.series(series)
.render()
setInterval(() => {
series = series.map((d,i) => {
return {
name: d.name,
data: new Array(7).fill(1).map((dd, ii) => {
return Math.floor(Math.random() * 200) + i * 200
})
}
})
console.log(series);
line
.dataX(dataX)
.series(series)
.render()
}, 4000)
</script>
</body>
</html>
想预览和下载demo的朋友可以移步原文
原文地址 http://www.bettersmile.cn
d3.js 教程 模仿echarts折线图的更多相关文章
- d3.js 教程 模仿echarts柱状图
由于最近工作不是很忙,隧由把之前的charts项目用d3.js重写的一下,其实d3.js文档很多,但是入门不是很难,可是想真的能做一个完成的,交互良好的图还是要下一番功夫的.今天在echarts找到了 ...
- d3.js 教程 模仿echarts legend功能
上一节记录没有加上echarts的legend功能,这一小节补一下. 1. 数据 我们可以从echarts中看出,折线数据并不是我们传进入的原始数据(多数情况下我们也不会修改原始数据),而是原始数组的 ...
- 【D3.js】Focus + Context 折线图
利用D3.js库实现Focus+Context的折线图.读取data.tsv文件数据 index.html <!DOCTYPE html> <meta charset="u ...
- vue使用axios读取本地json文件来显示echarts折线图
编辑器:HBuilderx axios文档:http://www.axios-js.com/zh-cn/docs/ echarts实例:https://echarts.apache.org/examp ...
- 实现Echarts折线图的虚实转换
需求:医院的体温单,在统计体温时,对于正常情况下统计的体温数据,需要显示实线:对于进行物理降温后统计的体温数据,需要显示虚线. 现有的体温单是运用 Echarts 折线图,统一用实线显示.因此在这基础 ...
- echarts折线图动态改变数据时的一个bug
echarts折线图中当增加dataZoom,修改start大于0的时候,会出现折线混乱,变成竖直的线,绘制有问题. 解决方法,在dataZoom中增加filterMode: 'empty' http ...
- ECharts折线图堆叠设置为不堆叠的方法
下图是ECharts折线图堆叠的官方源码,设置折线图不堆叠只需要将每一个stack的值设置为不一样的名称或者将stack属性删除即可. option = { title: { text: '折线图堆叠 ...
- echarts折线图,数据切换时(最近七天)绘图不合理现象
echarts折线图,当进行数据切换时存在绘制不合理的问题,数据没错,但绘制不对. 两个0之间的连线应该是平滑直线,如图: 正确的显示: 解决: 在myCharts.setOption(option) ...
- echarts折线图--数据交互
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...
随机推荐
- tf serving的使用
tensorflow_model_server --port=6000 --model_name=text_lstm --model_base_path=/home/guoyingmei/test/t ...
- 【Android - 组件】之Activity生命周期的全面分析
Activity是Android四大组件之首,其重要性不言而喻,Activity的生命周期更是我们了解Android工作机制的重中之重.我们一般将Activty的生命周期做两种情况下的理解,即正常情况 ...
- Chapter 02—Creating a dataset(Part1)
一. 数据集 1. 在R语言中,进行数据分析的第一步是创建一个包含待研究数据并且符合要求的数据集. · 选择装数据的数据结构 · 把数据装入数据结构中 2. 理解数据集 (1)数据集通常是矩形的数据列 ...
- 复习sed实例操作
第6周复习课(5月2日) 课程内容: 复习 扩展1.打印某行到某行之间的内容http://ask.apelearn.com/question/5592.sed转换大小写 http://ask.apel ...
- Python-车牌识别
一.车牌识别系统的用途与技术车牌识别系统(Vehicle License Plate Recognition,VLPR) 是计算机视频图像识别技术在车辆牌照识别中的一种应用.车牌识别在高速公路车辆管理 ...
- C#语法--委托,架构的血液
委托的定义 什么是委托? 委托实际上是一种类型,是一种引用类型. 微软用delegate关键字来声明委托,delegate与int,string,double等关键字一样.都是声明用的. 下面先看下声 ...
- 01Shell入门02-echo和printf
输出方式 小知识 echo echo -e 可以控制字体颜色和背景颜色输出 示例 echo -e "\033[41;36m Hello world \033[0m" [root@h ...
- MySQL必知必会(正则表达式)
SELECT prod_name FROM products ' #检索列prod_name包含文本1000的所有行. ORDER BY prod_name; SELECT prod_name FRO ...
- 使用ASP.NET Core 3.x 构建 RESTful API - 3.3 状态码、错误/故障、ProblemDetails
HTTP状态码 HTTP状态码会告诉API的消费者以下事情: 请求是否执行成功了 如果请求失败了,那么谁为它负责 HTTP的状态码有很多,但是Web API不一定需要支持所有的状态码.HTTP状态码一 ...
- Undefined symbols for architecture x86_64"_OBJC_CLASS_$_QQApiInterface 怎么搞
今天上午报了一个这样的错误 解决办法 如此如此 ~~ 然后编译 看看报的什么错误 还是不行的话就重新导入三方库 添加依赖库 结果build success