[英]Creating axis from array of strings in D3?
I've created a basic bar chart in d3 from an array of integers. 我已经在d3中使用整数数组创建了基本的条形图。
let maxWidth = $('body').width();
let chartWidth = maxWidth * 0.75; // also arbitrary
let chartHeight = chartWidth / _GoldenRatio;
let barWidth = (chartWidth / dataArray.length) - horizontalSpacing;
let barHeightUnit = chartHeight / d3.max(dataArray);
let mainChart = d3.select(containerSelector)
.append('svg')
.attr('width', chartWidth)
.attr('height', chartHeight);
mainChart.selectAll("rect")
.data(dataArray)
.enter()
.append("rect")
.attr("class", "bar")
.attr("height", function(d, i) { return (d * barHeightUnit) })
.attr("width",barWidth)
.attr("x", function(d, i) { return i * (barWidth + horizontalSpacing) + horizontalSpacing })
.attr("y", function(d, i) { return chartHeight - (d * barHeightUnit) });
I do this a few times with a few different arrays. 我用几个不同的数组做了几次。 Each list of integers corresponds with a list of strings that I'd like to display along the x-axis.
每个整数列表都对应于一个我希望沿x轴显示的字符串列表。 Each string will lie below one bar to label it.
每个字符串将位于一个条下面,以对其进行标记。
I can't figure out a way to do this easily with d3 or d3-axis. 我想不出一种用d3或d3轴轻松实现此目的的方法。 What is an easy way to construct an axis from this list of strings?
从此字符串列表构造轴的简单方法是什么?
Hope this snippet using d3.v4 helps. 希望使用d3.v4的这段代码对您有所帮助。
var margin = { top: 100, right: 100, bottom: 100, left: 100 }, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var x = d3.scaleBand() .range([0, width]) .domain(["apple", "orange", "banana", "grapefruit"]); var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x));
<script src="https://d3js.org/d3.v4.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.