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的更多相关文章

  1. [D3] Build an Area Chart with D3 v4

    Similar to line charts, area charts are great for displaying temporal data. Whether you’re displayin ...

  2. [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 ...

  3. [D3] Build a Scatter Plot with D3 v4

    Scatter plots, sometimes also known as bubble charts, are another common type of visualization. They ...

  4. Highcharts - Bar Chart & Column Chart

    1. 条形图(Bar Chart)需要的数据格式类型如下: ["Luke Skywalker", "Darth Vader", "Yoda" ...

  5. 使用 angular directive 和 json 数据 D3 随着标签 donut chart演示样本

    使用angular resource载入中priorityData.json中间json数据,结合D3绘制甜甜圈图.执行index.html其结果见于图.: priorityData.json中jso ...

  6. [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 ...

  7. d3可视化实战02:理解d3数据驱动的真正含义

    前文中已经提到,SVG从诞生之初起就可以非常方便地使用javascript脚本语言来进行其DOM对象的控制.当然,控制的方法有很多,有直接控制SVG对象的方法,例如使用原生js:有帮你封装一下图形接口 ...

  8. 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; }) 错误 ...

  9. kendo column chart

     目录 1.用js操作chart, 2.tooltip template鼠标悬浮显示内容, 3.双坐标轴,axisCrossingValues: [0, 30],3指的是跨越横坐标轴标签项数,显示在右 ...

随机推荐

  1. [Python] String Join

    Let's introduce a new string method, join: >>> nautical_directions = "\n".join([& ...

  2. android中9-patch图片的使用

    看了非常多文章的介绍,9.png图片有两种区域:可扩展区和内容显示区. 弄了半天才明确什么叫做可扩展区,什么叫做内容显示区. 分享一下自己的理解. 下图是某博客的截图: 图片来自:http://blo ...

  3. js02---字符串

    <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...

  4. zoj 1119 / poj 1523 SPF (典型例题 求割点 Tarjan 算法)

    poj : http://poj.org/problem?id=1523 如果无向图中一个点 u 为割点 则u 或者是具有两个及以上子女的深度优先生成树的根,或者虽然不是一个根,但是它有一个子女 w, ...

  5. 带你底层看Sqoop如何转换成MapReduce作业运行的(代码程序)

    补充 其实啊,我们知道,sqoop在运行的时候,最终会去转换成mapreduce作业,这个很简单,不多赘述.直接贴出来. 具体这些怎么运行的,见我如下这篇博客.这里只做一个引子. Sqoop Impo ...

  6. Java学习笔记十

    网络编程: 一.osi和TCP协议对照: 二.通讯三要素: 三.InetAddress对象简述: import java.net.InetAddress; import java.net.Unknow ...

  7. array01.js

    //1.获取指定范围内的随机数 function getRadomNum(min,max){ return Math.floor(Math.random() * (max - min + 1)) + ...

  8. nodejs学习(二)--express热更新nodemon,自启动项目

    一.说一下 每次修改文件,我们都需要重启服务器npm start,很麻烦,所以使用引入nodemon插件,解决这个问题,实现保存文件,即自启动刷新项目 二.直接开码 npm install nodem ...

  9. Java 学习(15):Java 数据结构

    Java 数据结构 Java工具包提供了强大的数据结构.在Java中的数据结构主要包括以下几种接口和类: 枚举(Enumeration) 位集合(BitSet) 向量(Vector) 栈(Stack) ...

  10. Repractise基础篇:Web应用开发七日谈

    Repractise基础篇:Web应用开发七日谈 本来想的仅仅是画一个例如以下的七日图来说说Web开发的.随后又想了想这似乎是一个非常棒的Web开发相关的知识介绍.应用开发是一个非常有意思的循环,多数 ...