[D3] Build a Scatter Plot with D3 v4
Scatter plots, sometimes also known as bubble charts, are another common type of visualization. They’re extremely versatile thanks to their ability to display multiple dimensions of data simultaneously using x and y position, opacity, color, and even shape. This lesson introduces the SVG circle element as part of building a robust scatter plot.
var margin = {
top: 10,
right: 20,
bottom: 65,
left: 40
};
var width = 400 - margin.left - margin.right;
var height = 600 - margin.top - margin.bottom;
var svg = d3.select('.chart')
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.call(responsivefy)
.append('g')
.attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')');
/**
* Load data
*/
d3.json('../data/data2.json', function (err, data) {
/**
* Add Y axis
*/
var yScale = d3.scaleLinear()
.domain(d3.extent(data, (d) => d.expectancy))
.range([height, 0])
.nice();
var yAxis = d3.axisLeft(yScale);
svg.call(yAxis);
/**
* Add X axis
*/
var xScale = d3.scaleLinear()
.domain(d3.extent(data, d => d.cost))
.range([0, width])
.nice();
var xAxis = d3.axisBottom(xScale);
svg
.append('g')
.attr('transform', `translate(0, ${height})`)
.call(xAxis);
// For circle, we need scaleSqrt
var rScale = d3.scaleSqrt()
.domain([0, d3.max(data, d => d.population)])
.range([0, 40]);
// Create some container to contain the circles
var circles = svg.selectAll('.ball')
.data(data)
.enter()
.append('g')
.attr('class', 'ball')
.attr('transform', d => {
return `translate(${xScale(d.cost)}, ${yScale(d.expectancy)})`
});
// Add circle to each containers
circles
.append('circle')
.attr('cx', 0)
.attr('cy', 0)
.attr('r', d => rScale(d.population))
.style('opacity', 0.5)
.style('fill', 'steelblue');
// Add text
circles
.append('text')
.style('text-anchor', 'middle')
.style('fill', 'black')
.attr('y', 4)
.text(d => d.code)
});
function responsivefy(svg) {
// get container + svg aspect ratio
var container = d3.select(svg.node().parentNode),
width = parseInt(svg.style("width")),
height = parseInt(svg.style("height")),
aspect = width / height;
// add viewBox and preserveAspectRatio properties,
// and call resize so that svg resizes on inital page load
svg.attr("viewBox", "0 0 " + width + " " + height)
.attr("preserveAspectRatio", "xMinYMid")
.call(resize);
// to register multiple listeners for same event type,
// you need to add namespace, i.e., 'click.foo'
// necessary if you call invoke this function for multiple svgs
// api docs: https://github.com/mbostock/d3/wiki/Selections#on
d3.select(window).on("resize." + container.attr("id"), resize);
// get width of container and resize svg to fit it
function resize() {
var targetWidth = parseInt(container.style("width"));
svg.attr("width", targetWidth);
svg.attr("height", Math.round(targetWidth / aspect));
}
}
[D3] Build a Scatter Plot with D3 v4的更多相关文章
- [D3] Build a Line Chart with D3 v4
Line charts are often used to plot temporal data, like a stock price over time. In this lesson we’ll ...
- [D3] Build an Area Chart with D3 v4
Similar to line charts, area charts are great for displaying temporal data. Whether you’re displayin ...
- [D3] Build a Column Chart with D3 v4
Column and bar charts are staples of every visualization library. They also make a great project for ...
- [D3] 9. Scatter Plot
Up until now we've just looked at bar charts. A handy chart, no doubt, but D3 offers a variety of ch ...
- [D3] Animate Chart Axis Transitions in D3 v4
When the data being rendered by a chart changes, sometimes it necessitates a change to the scales an ...
- [D3] Load and Inspect Data with D3 v4
You probably use a framework or standalone library to load data into your apps, but what if that’s o ...
- d3.svg.line()错误:TypeError: d3.svg.line is not a function
var line_generator= d3.svg.line() .x(function (d,i) { return i; }) .y(function (d) { return d; }) 错误 ...
- d3可视化实战02:理解d3数据驱动的真正含义
前文中已经提到,SVG从诞生之初起就可以非常方便地使用javascript脚本语言来进行其DOM对象的控制.当然,控制的方法有很多,有直接控制SVG对象的方法,例如使用原生js:有帮你封装一下图形接口 ...
- Matplotlib学习---用matplotlib画散点图,气泡图(scatter plot, bubble chart)
Matplotlib里有两种画散点图的方法,一种是用ax.plot画,一种是用ax.scatter画. 一. 用ax.plot画 ax.plot(x,y,marker="o",co ...
随机推荐
- js---16继承
123 instanceof Number;//false,要左边是对象右边是函数 typeof 123 ; //number new Number(123) instanceof Number; / ...
- .Net写的比较清晰的接口
尼玛,隔行如隔山. .Net真操蛋. /// <summary> /// 加入群 /// </summary> /// <returns></returns& ...
- 在英语中,in,on,at的用法是?
在几点:at xx:xx ,在那月: in Dec./Jan.……, 在那日:on Thur./Mon.……,on Jan. 16th 时间前面 at, 年月日前面如果有具体的日子,就是具体的哪一天 ...
- Oracle 练习
--简单的select语句select deptno,dname,loc from DEPT where deptno='40';--描述表结构 部门表desc dept;--雇员表desc emp; ...
- NYOJ 927 The partial sum problem 【DFS】+【剪枝】
The partial sum problem 时间限制:1000 ms | 内存限制:65535 KB 难度:2 描写叙述 One day,Tom's girlfriend give him a ...
- jquery的图片轮播 模板类型
先说一下用到的几个重要的事件 j jQuery on()方法是官方推荐的绑定事件的一个方法. $(selector).on(event,childSelector,data,function,map) ...
- GestureDetector- 滑屏手势方式实现
今天做的项目中,需要使用滑屏来调出一个界面,经过自己的尝试,结合网上的方法,成功实现了. 代码如下 package com.example.text; import android.app.Activ ...
- thinkphp杂项功能(主干)
thinkphp杂项功能(主干) 一.总结 1.杂项功能:杂项里面我需要有点印象的是五个:缓存,多语言,图像处理,文件处理,单元测试 二.thinkphp杂项功能(主干) thinkphp扩展杂项功能 ...
- Java学习笔记三.3
9.异常处理:Java中的异常处理对象就是将以前的if语句进行的判断进行抽象化,并形成的一套错误处理体系.最顶端是Throwable,接着是Error,Exception,其中Exception又明显 ...
- vue打包添加样式兼容前缀
在ios8 版本上的h5对flex的支持不太好,需要有兼容的写法. vue-cli自带了postCss autoprefixer 进行兼容处理,配置如下 在vue-loader.config.js中开 ...