[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 combining the essential pieces of D3 like selections, scales, axes, and SVG elements. This lesson walks you through the process of creating an essential chart type with all the required components.
The dataset looks like:
var data = [
{score: 63, subject: 'Mathematics'},
{score: 82, subject: 'Geography'},
{score: 74, subject: 'Spelling'},
{score: 97, subject: 'Reading'},
{score: 52, subject: 'Science'},
{score: 74, subject: 'Chemistry'},
{score: 97, subject: 'Physics'},
{score: 52, subject: 'ASL'}
];
We want 'score' map to 'Y' axis and 'subject' map to 'X' axis.
For 'Y' axis is pretty, we can use 'scaleLinear'.
For 'X' axis we can use 'scaleBand'.
var data = [
{score: 63, subject: 'Mathematics'},
{score: 82, subject: 'Geography'},
{score: 74, subject: 'Spelling'},
{score: 97, subject: 'Reading'},
{score: 52, subject: 'Science'},
{score: 74, subject: 'Chemistry'},
{score: 97, subject: 'Physics'},
{score: 52, subject: 'ASL'}
]; var margin = { top: 10, right: 20, bottom: 65, left: 30 };
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 + ')'); /**
* Add Y axis
*/
var yScale = d3.scaleLinear()
.domain([0, 100])
.range([height, 0]);
var yAxis = d3.axisLeft(yScale);
svg.call(yAxis); /**
* Add X axis
*/
var xScale = d3.scaleBand()
.padding(0.2)
.domain(data.map(d => d.subject))
.range([0, width]); var xAxis = d3.axisBottom(xScale)
.ticks(5)
.tickSize(10)
.tickPadding(5);
svg
.append('g')
.attr('transform', `translate(0, ${height})`)
.call(xAxis)
.selectAll('text')
.attr('text-anchor', 'end')
.attr('transform', 'rotate(-45)'); // Rotate the text so texts won't conflict /**
* Draw the columns
*/
svg.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('x', d => xScale(d.subject))
.attr('y', d => yScale(d.score))
.attr('width', d => xScale.bandwidth())
.attr('height', d => height-yScale(d.score)); 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 Column Chart with D3 v4的更多相关文章
- [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 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 a Scatter Plot with D3 v4
Scatter plots, sometimes also known as bubble charts, are another common type of visualization. They ...
- Highcharts - Bar Chart & Column Chart
1. 条形图(Bar Chart)需要的数据格式类型如下: ["Luke Skywalker", "Darth Vader", "Yoda" ...
- 使用 angular directive 和 json 数据 D3 随着标签 donut chart演示样本
使用angular resource载入中priorityData.json中间json数据,结合D3绘制甜甜圈图.执行index.html其结果见于图.: priorityData.json中jso ...
- [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可视化实战02:理解d3数据驱动的真正含义
前文中已经提到,SVG从诞生之初起就可以非常方便地使用javascript脚本语言来进行其DOM对象的控制.当然,控制的方法有很多,有直接控制SVG对象的方法,例如使用原生js:有帮你封装一下图形接口 ...
- 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; }) 错误 ...
- kendo column chart
目录 1.用js操作chart, 2.tooltip template鼠标悬浮显示内容, 3.双坐标轴,axisCrossingValues: [0, 30],3指的是跨越横坐标轴标签项数,显示在右 ...
随机推荐
- Intersection between a 2d line and a conic in OpenCASCADE
Intersection between a 2d line and a conic in OpenCASCADE eryar@163.com Abstract. OpenCASCADE provid ...
- jquery09--Callbacks : 回调对象
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...
- 如何使iframe外部的超级链接的页面在iframe中打开
如何使iframe外部的超级链接的页面在iframe中打开,有以下两种方法: 一.html方法: <iframe name="a1"></iframe> & ...
- IBM磁盘阵列及文件系统的管理
一.几个基本概念 物理卷(PV):一个物理卷指一块硬盘 卷组(VG):卷组是可用物理硬盘的集合,可以逻辑地看成一块大硬盘 物理分区(PP):卷组中物理卷划分成固定大小的块(缺省为4MB) 逻辑卷(LV ...
- MD基本语法介绍
Markdown基本语法介绍 前言 文本编辑器一般用的有富文本编辑器(也就是Word)和md了,但是wold太过于花里胡哨很多功能都用不上,所以就选择md了,简单实用,一对于我来说一般就用标题和列表就 ...
- readonly&&declare&&unset &&export&&env环境变量
readonly命令用于定义只读shell变量和shell函数.readonly命令的选项-p可以输出显示系统中所有定义的只读变量. 选项 -f:定义只读函数: -a:定义只读数组变量: -p:显示系 ...
- 数据库事务及其EF中如何处理事务
一.基础知识 1) 使用事务级别ReadUnCommited 会产生脏读现像,意味着读取到的为UnCommited(未提交)的数据.怎么理解呢?在使用该隔离级别的事务开始后.更新了数据 ...
- Spring3 整合MyBatis3 配置多数据源 动态选择SqlSessionFactory(转)
1. Spring整合MyBatis切换SqlSessionFactory有两种方法,第一. 继承SqlSessionDaoSupport,重写获取SqlSessionFactory的方法.第二.继承 ...
- [TypeScript] Shallow copy object by using spread opreator
For example we have an object: const todo = { text: "Water the flowers", completed: false, ...
- ZOJ 3587 Marlon's String 扩展KMP
链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3587 题意:给出两个字符串S和T.S,T<=100000.拿出 ...