[D3] Build a Column Chart with D3 v4
with build Column v4 Chart D3
2023-09-14 08:59:18 时间
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)); } }
相关文章
- [RxJS] Build an Event Combo Observable with RxJS (takeWhile, takeUntil, take, skip)
- [React] Update Application State with React Apollo ApolloConsumer Component
- [Poi] Customize Babel to Build a React App with Poi
- [D3] Build a Scatter Plot with D3 v4
- [Docker] Build a Simple Node.js Web Server with Docker
- [Angular-Scaled Web] 9. Control your promises with $q
- [Unit testing RxJS] Test hot observables with marbles
- [Typescript] Configuration Inheritance with Extends
- [Javascript] Build lodash.omitBy and lodash.pickBy with Object.fromEntries + Object.entry (isomorphism)
- [RxJS] Build an Event Combo Observable with RxJS (takeWhile, takeUntil, take, skip)
- [Sping Boot] Build a REST CRUD API with Hibernate
- [HTML5] Build Flexible HTML with HTMLTemplates using Slots and Web Components
- [Javascript] Use JavaScript's for-in Loop on Objects with Prototypes
- [Node.js] Manage Configuration Values with Environment Variables
- [Poi] Use Poi to Build an Index.js with Modern JavaScript Features
- [Angular] Setup automated deployment with Angular, Travis and Firebase
- [CSS] Build Responsive CSS Layouts with Tachyons
- [Angular2] Build reuseable template with ngTemplateOutlet
- [Docker] Build a Simple Node.js Web Server with Docker
- [RxJS] Combining Streams with CombineLatest
- [Angular 2] Pipes with Multiple Parameters
- [Grunt] Cleaning your build folder with grunt-contrib-clean
- how is json model initialized with json data
- Attachment multiple read API - performance with regular expression
- 成功解决error: Microsoft Visual C++ 14.0 or greater is required. Get it with “Microsoft C++ Build Tools“
- 成功解决error: Microsoft Visual C++ 14.0 or greater is required. Get it with “Microsoft C++ Build Tools“
- Tutorial: Build a Spring WebMVC App with Primefaces
- InstallShield Build错误:Internal build error 6041
- More than one file was found with OS independent path 'META-INF/LICENSE' | Error:Could not read buildintermediatestypedefs.txt (系统找不到指定的文件。)
- leetcode 693. Binary Number with Alternating Bits