[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指的是跨越横坐标轴标签项数,显示在右 ...
随机推荐
- html5页面怎么播放音频和视频
html5页面怎么播放音频和视频 一.总结 一句话总结:html5 音频和视频标签:(audio And video),局限是不同浏览器对音频视频的格式支持很让人头痛 1.最基础的音频和视频标签的使用 ...
- js call 和 apply
前言 call 和 apply 都是为了改变某个函数运行时的 context 即上下文而存在的,换句话说,就是为了改变函数体内部 this 的指向. call 和 apply二者的作用完全一样,只是接 ...
- PCA and Whitening on natural images
Step 0: Prepare data Step 0a: Load data The starter code contains code to load a set of natural imag ...
- 博弈论 SG函数(模板) HDU 1848 Fibonacci again and again
Fibonacci again and again Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Jav ...
- ajax处理响应(三)
一旦脚本调用了send方法,浏览器就会在后台发送请求到浏览器.因为请求是在后台处理的,所以Ajax依靠事件来通知你这个请求的进度的进展情况,在上个随笔的里,使用handleResponse函数 ...
- C/C++(基础-常量,类型转换)
字符 char ascII码表 #include<stdio.h> int main() { unsigned char ch; for(ch = 0;ch < 128;ch++) ...
- FreeModbus TCP
一.Modbus TCP协议格式 Modbus TCP协议数据格式如下图所示: MBAP报文头: Modbus TCP与Modbus RTU相比,没有检验码,也没有所谓的地址码,并且在RTU协议的基础 ...
- 传输资料在100MB以上的 传输介质选择
传输资料在100MB以上的 硬盘-->千兆局域网-->硬盘 硬盘-->USB3.0-->硬盘 硬盘-->数据线-->硬盘 传输速率 USB 的理论传输值 USB2. ...
- js10---call方法总结
<html> <body> <script type="text/javascript"> function Obj(x, y){ this.x ...
- JS ajax 应用 (下拉列表联动)
<script language="javascript"> var http_request=false; function send_request( ...