D3条形图添加图例

时间:2018-11-28 11:26:12

标签: javascript d3.js bar-chart legend

我已经在d3中制作了条形图,但是我在两件事上挣扎。 首先,我想添加一个图例,因为我有2个不同的小节,所以我希望人们知道每个小节是什么。

第二个我想从json文件而不是此文件中加载数据:

var data = [
  {
    "year":1970,
    "count1":1,
    "count2":0
  },
  {
    "year":1975,
    "count1":1,
    "count2":0
  },
  {
    "year":1980,
    "count1":1,
    "count2":1
  }]

但是当我尝试使用json文件时,我的地图函数给出了一个错误。

我的代码:

var svgSelect = d3.select("svg")
var width = 1020
var height = 900
var margin = {top: 35, right: 25, bottom: 35, left: 50}
var paddingBars = .2
var axisTicks = {amount: 25, outerSize: 0}

var svg = svgSelect
    .append("svg")
    .attr("widht", width)
    .attr("height", height)
    .append("g")
    .attr("transform", `translate(${margin.left},${margin.top})`)

var xScale0 = d3.scaleBand().range([0, width - margin.left - margin.right]).padding(paddingBars)
var xScale1 = d3.scaleBand()
var yScale = d3.scaleLinear().range([height - margin.top - margin.bottom, 0])

var xAxis = d3.axisBottom(xScale0).tickSizeOuter(axisTicks.outerSize)
var yAxis = d3.axisLeft(yScale).ticks(axisTicks.amount).tickSizeOuter(axisTicks.outerSize)

xScale0.domain(data.map(d => d.year))
xScale1.domain(['count1', 'count2']).range([0, xScale0.bandwidth()])
yScale.domain([0, d3.max(data, d => d.count1 > d.count2 ? d.count1 : d.count2)])

var year = svg.selectAll(".year")
  .data(data)
  .enter().append("g")
  .attr("class", "year")
  .attr("transform", d => `translate(${xScale0(d.year)},0)`)

/* Add count1 bars */
year.selectAll(".bar.count1")
  .data(d => [d])
  .enter()
  .append("rect")
  .attr("class", "bar count1")
.style("fill","blue")
  .attr("x", d => xScale1('count1'))
  .attr("y", d => yScale(d.count1))
  .attr("width", xScale1.bandwidth())
  .attr("height", d => {
    return height - margin.top - margin.bottom - yScale(d.count1)
  })

/* Add coun2 bars */
year.selectAll(".bar.count2")
  .data(d => [d])
  .enter()
  .append("rect")
  .attr("class", "bar count2")
.style("fill","red")
  .attr("x", d => xScale1('count2'))
  .attr("y", d => yScale(d.count2))
  .attr("width", xScale1.bandwidth())
  .attr("height", d => {
    return height - margin.top - margin.bottom - yScale(d.count2)
  })

// Add the X Axis
svg.append("g")
   .attr("class", "x axis")
   .attr("transform", `translate(0,${height - margin.top - margin.bottom})`)
   .call(xAxis);

// Add the Y Axis
svg.append("g")
   .attr("class", "y axis")
   .call(yAxis)

0 个答案:

没有答案