[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 ... 
随机推荐
- Spring MVC : Java模板引擎 Thymeleaf (三)
			以下以构造一个表单開始,解说 Thymeleaf的使用方法. 为了演示方便,还是以经典的注冊为例. 这是Thymeleaf的form的形式, <form action="#" ... 
- 思科2960trunk vlan配置及路由IP配置
			en conf t vlan id end conf t inter rang gi 0/0/1-x switchport access vlan id no shutdown exit (confi ... 
- Js将类数组转化为数组
			说起伪数组,大家可能会想到arguments, 这个我们函数参数的一个类数组,是类数组的代表. 1.拥有length属性,可以使用下标来访问元素,这两点和数组相同. 2.不能使用数组的方法,他们不能使 ... 
- 搭建Spark源码研读和代码调试的开发环境
			转载自https://github.com/linbojin/spark-notes/blob/master/ide-setup.md 搭建Spark源码研读和代码调试的开发环境 工欲善其事,必先利其 ... 
- errpt命令
			errpt –a 详细信息 errpt -a –s [TIMESTAMP] errpt –aj [IDENTIFIER] errclear 清除(后面接参数) errpt -aj BFE4C025 ... 
- C/C++(函数)
			函数 函数三要素:函数名,参数,返回值 重点研究函数的输入输出 随机数函数 //产生一组随机数 #include<stdio.h> #include<stdlib.h> #in ... 
- ZJOI2017线段树
			ZJOI2017线段树 题意:  给你一颗广义线段树,太长了,自己去看. 题解:  直接上zkw那一套,把闭区间换成开区间,就是把取\([l,r]\),变成取\([l-1,l-1],[r+1,r+ ... 
- 【MongoDB】mongodump and mongorestore of mogodb
			The another tool will be mentioned in this blog, namely mongodump and mongorestore. General speaking ... 
- mac自己定义tree命令
			编辑文件: vim ~/.bash_profile 在文件末尾追加: alias tree="find . -print | sed -e 's;[^/]*/;|____;g;s;____| ... 
- android 弹幕评论效果
			纯粹依照自己的想法仿照b站的弹幕写的一个demo,不知道正确的姿势怎么样的. demo下载地址 首先.一条弹幕就是一个textview public abstract class Danmu exte ... 
