D3 js ranged bar chart [closed]

2019-09-14 01:39发布

问题:

I'm new to d3 js. I'm looking for a chart like this one done in highcharts. In highcharts it is called column range graph. Is there any way to achieve this.

When I search in google the best thing I can get is a basic bar chart. Can any one help me how to make it a ranged graph?

回答1:

Imagine I have dataset like this:

//these are the various categories 
    var categories = ['', 'Accessories', 'Audiophile', 'Camera & Photo', 'Cell Phones', 'Computers', 'eBook Readers', 'Gadgets', 'GPS & Navigation', 'Home Audio', 'Office Electronics', 'Portable Audio', 'Portable Video', 'Security & Surveillance', 'Service', 'Television & Video', 'Car & Vehicle'];
//these are the various categories cost
 var dollars = [[100,213], [75,209], [50,190], [100,179], [140,156], [138, 209], [90, 190], [65,179], [100, 213], [100, 209], [50, 190], [76,179], [45,156], [80,209], [75,190], [55,190]];

Here in the dataset Car&Vehicle will have a cost range from 55$ to 190$. Here Television & Video will have a cost range from 75$ to 190$ depending on quality.

Let's make x scale.

var xscale = d3.scale.linear()
  .domain([10, 250])//minimum cast can be 10$ and maximum cost 250$
  .range([0, 722]);

Lets make the rectangle bars.

var chart = canvas.append('g')
      .attr("transform", "translate(150,0)")
      .attr('id', 'bars')
      .selectAll('rect')
      .data(dollars)
      .enter()
      .append('rect')
      .attr('height', 19)
      .attr({
        'x': function(d) {
          return xscale(d[0]);//this defines the start position of the bar
        },
        'y': function(d, i) {
          return yscale(i) + 19;
        }
      })
      .style('fill', function(d, i) {
        return colorScale(i);
      })
      .attr('width', function(d) {
        return 0;
      });

Now for transition the width of the bar will be:

var transit = d3.select("svg").selectAll("rect")
  .data(dollars)
  .transition()
  .duration(1000)
  .attr("width", function(d) {
    return xscale(d[1]) - xscale(d[0]);//width of the bar will be upper range - lower range.
  });

Full working code here.



回答2:

Your link to a basic bar chart does not work. That just looks like a horizontal bar chart, of which there are many exapmles. Here is one: http://bl.ocks.org/mbostock/2368837