[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指的是跨越横坐标轴标签项数,显示在右 ...
随机推荐
- [ES2017] Iterate over properties of an object with ES2017 Object.entries()
The Object.entries() function is an addition to the ECMAscript scpec in Es2017. This allows us to it ...
- HDU 2886 Lou 1 Zhuang
思维好重要.. 对于n+m == k , 当n == m || abs(n-m) == 1 时n*m取得最大值. 设 s = x*(l-x),s = lx-x^2.其导函数为 s' = -1/2x + ...
- WIN10 10招
还有不到两个月的时间,7 月 29 日 Windows 10 就将正式公布,在此之前已经有不少的用户已经使用上了 Windows 10 的预览版.对于那些苦等 Windows 10 的用户来说,幸福非 ...
- Linux Unix shell 编程指南学习笔记(第二部分)
第七章 正則表達式介绍 匹配行首与行尾 匹配数据集 职匹配字母和数字 句点 "." 匹配随意单字符. ^,在行首 匹配字符串或字符序列,如查询当前文件夹下的全部文件夹: ls - ...
- Bmob移动后端云服务平台--Android从零開始--(一)何为Bmob
Bmob移动后端云服务平台--Android从零開始--(一)何为Bmob 在正式的项目开发中,单client不能满足我们的需求,须要实现client与服务端的连接. 而在编写Android服务端代码 ...
- js---16原型链
var p = {name:"sss"}; var c2 = Object.create(p,{age:32,salar:"eee"});//c2就继承了p的属 ...
- FormData是什么
FormData是什么 一.总结 一句话总结:利用 FormData 对象,可以通过JavaScript键值对来模拟一系列表单控件,还可以使用 XMLHttpRequest的send() 方法来异步提 ...
- 关于jquery的事件命名空间
在多人协作的前端开发中,或许会遇到一个问题:几个开发人员都给一个元素添加了同样的事件,但是又有开发人员想要解除掉元素身上的某个事件效果,这时候操作起来就有些麻烦,需要用到jquery给我们提供的事件命 ...
- javafx Hanoi
Netbean java8 source code :http://files.cnblogs.com/files/rojas/HNT.zip screenshot: 1 model /* ...
- unity3d编程日志
2014/4/27 编写脚本的时候,加入了中文凝视,发现console面板有非常多不可思议的bug.查了一下发现是由于monodevelop脚本中文凝视报错,而英文凝视不会受影响. 解决方法:把凝视放 ...