使用条形图可视化数据

时间:2017-03-19 15:40:07

标签: javascript d3.js

我的条形图看起来像这样。

enter image description here

我想像这样配置xAxis(底部的年份)。 我将重复一年。如何删除重复年份?

enter image description here

这是我的代码。

    <!DOCTYPE html>
<meta charset="utf-8">
<style>

    body {
        font: 10px sans-serif;
    }

    .axis path,
    .axis line {
        fill: none;
        stroke: #000;
        shape-rendering: crispEdges;
    }

    .bar {
        fill: orange;
    }

    .bar:hover {
        fill: orangered ;
    }

    .x.axis path {
        display: none;
    }

    .d3-tip {
        line-height: 1;
        font-weight: bold;
        padding: 12px;
        background: rgba(0, 0, 0, 0.8);
        color: #fff;
        border-radius: 2px;
    }

    /* Creates a small triangle extender for the tooltip */
    .d3-tip:after {
        box-sizing: border-box;
        display: inline;
        font-size: 10px;
        width: 100%;
        line-height: 1;
        color: rgba(0, 0, 0, 0.8);
        content: "\25BC";
        position: absolute;
        text-align: center;
    }

    /* Style northward tooltips differently */
    .d3-tip.n:after {
        margin: -1px 0 0 0;
        top: 100%;
        left: 0;
    }
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>
<script>

    var margin = {top: 40, right: 20, bottom: 30, left: 40},
        width = 960 - margin.left - margin.right,
        height = 500 - margin.top - margin.bottom;

    var formatPercent = d3.format("0");

    var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .1);

    var y = d3.scale.linear()
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left")
        .tickFormat(formatPercent);

    var tip = d3.tip()
        .attr('class', 'd3-tip')
        .offset([-10, 0])
        .html(function(d) {
            return "<strong>Frequency:</strong> <span style='color:red'>" + d[1] + "</span>";
        })

    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.call(tip);

    var jonData = 'https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json';
    d3.json(jonData, function(error, data) {
        if(error){
            return console.warn(error);
        }
//        console.log(data.data);

        data = data.data;
        data.map(function(d)
        {
            var date = new Date(d[0]);

            console.log(date.getFullYear());
        });
        x.domain(data.map(function(d) { return d[0]; }));
        y.domain([0, d3.max(data, function(d) { return d[1]; })]);

        svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis);

        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis)
            .append("text")
            .attr("transform", "rotate(-90)")
            .attr("y", 6)
            .attr("dy", ".71em")
            .style("text-anchor", "end")
            .text("Gross Domestic Product, USA");

        svg.selectAll(".bar")
            .data(data)
            .enter().append("rect")
            .attr("class", "bar")
            .attr("x", function(d) { return x(d[0]); })
            .attr("width", x.rangeBand())
            .attr("y", function(d) { return y(d[1]); })
            .attr("height", function(d) { return height - y(d[1]); })
            .on('mouseover', tip.show)
            .on('mouseout', tip.hide)

    });

</script>

我正在关注此链接Using d3-tip to add tooltips to a d3 bar chart。我在这里做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

您的代码的主要问题是您使用的是序数量表。您可以使用序数标度(如您所见,条形图显示),但您必须创建 ad hoc 代码以消除标记。

“正确”的方法是使用时间刻度,因为您的数据与时间有关:

var x = d3.time.scale()
    .range([0, width]);

但是,您必须解析日期:

var timeFormat = d3.time.format("%Y-%m-%d")

data.forEach(function(d) {
    d[0] = timeFormat.parse(d[0]);
});

并且还要更改x域:

x.domain(d3.extent(data, function(d) {
    return d[0]
}));

以下是使用轴生成器中的ticks(10)进行更改的代码:

var margin = {
    top: 40,
    right: 20,
    bottom: 30,
    left: 40
  },
  width = 960 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

var formatPercent = d3.format("0");

var x = d3.time.scale()
  .range([0, width]);

var y = d3.scale.linear()
  .range([height, 0]);

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom")
  .ticks(15);

var yAxis = d3.svg.axis()
  .scale(y)
  .orient("left")
  .tickFormat(formatPercent);

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 + ")");

var timeFormat = d3.time.format("%Y-%m-%d")

var jonData = 'https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json';
d3.json(jonData, function(error, data) {
  if (error) {
    return console.warn(error);
  }

  data = data.data;

  data.forEach(function(d) {
    d[0] = timeFormat.parse(d[0]);
  });

  x.domain(d3.extent(data, function(d) {
    return d[0]
  }));
  y.domain([0, d3.max(data, function(d) {
    return d[1];
  })]);

  svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

  svg.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", ".71em")
    .style("text-anchor", "end")
    .text("Gross Domestic Product, USA");

  svg.selectAll(".bar")
    .data(data)
    .enter().append("rect")
    .attr("class", "bar")
    .attr("x", function(d) {
      return x(d[0]);
    })
    .attr("width", width / data.length)
    .attr("y", function(d) {
      return y(d[1]);
    })
    .attr("height", function(d) {
      return height - y(d[1]);
    })
    
});
body {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.bar {
  fill: orange;
}

.bar:hover {
  fill: orangered;
}

.x.axis path {
  display: none;
}
<script src="https://d3js.org/d3.v3.min.js"></script>