Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3 using a different X scale and Y scale domain for each selection

Here is the project on jsfiddle: http://jsfiddle.net/mLnB3/

I have data that is in this format:

var data = [
{
    "category": "Category1",
    "subcategories": [
        {
            "subcategory": "Subcategory1A",
            "comments": [
                {
                    "comment" : "1Acomment1",
                    "count": 8,
                },
                {
                    "comment": "1Acomment2",
                    "count": 7
                }
            ]
        },
        {
            "subcategory": "Subcategory1B",
            "comments": [
                {
                    "comment": "1Bcomment1",
                    "count": 11,
                }
            ]
        },
        {
            "subcategory": "Subcategory1C",
            "comments": [
                {
                    "comment": "1Ccomment1",
                    "count": 2,
                }
            ]
        }
    ]
},
{
    "category": "Category2",
    "subcategories": [
        {
            "subcategory": "Subcategory2A",
            "comments": [
                {
                    "comment": "2Acomment1",
                    "count": 6,
                },
                {
                    "comment": "2Acomment2",
                    "count": 9,
                },
                {
                    "comment": "2Acomment3",
                    "count": 9,
                },
                {
                    "comment": "2Acomment4",
                    "count": 9,
                }
            ]
        },
        {
            "subcategory": "Subcategory2B",
            "comments": [
                {
                    "comment": "2Bcomment1",
                    "count": 14
                }
            ]
        }
     ]
}

];

I want to create a bar chart for each category. So Category 1 will be a bar chart, Category 2 will be a bar chart, and so on (there are many more categories). Each category has a different number of subcategories and each subcategory has a different number of comments (ranging from 1 - 30). In each bar chart, the comments will be populating the X axis. So for each chart I need to produce something like this:

<svg id="Category1">
  <g>
    <g class="xAxis">...</g>
    <g class="yAxis">...</g>  
    <g class="subcategory" id="Subcategory1A">
      <g class="comment" id="1Acomment1">
        <rect height="8"></rect>
        <text>8</text>
      </g>
      <g class="comment" id="1Acomment2">
        <rect height="7"></rect>
        <text>7</text>
      </g>
    </g>
    <g class="subcategory" id="Subcategory1B">
      <g class="comment" id="1Bcomment1">
        <rect height="11"></rect>
        <text>11</text>
      </g>
    </g>
    <g class="subcategory" id="Subcategory1C">
      <g class="comment" id="1Ccomment1">
        <rect height="2"></rect>
        <text>2</text>
      </g>
    </g>
  </g> 
</svg>
<svg id="Category2">
...
</svg>

I'm using d3.select("body").selectAll("svg").data(data).enter().append("svg").... to create them all.

My problem is that since each different chart will have a different number of xAxis ticks I have no idea how to set the domain for the ordinal scale for each chart's xAxis. Same problem with the linear scale for the yAxis because I normally do [0, d3.max(...)] for that one, but that will be different for each bar chart as well.

This is what I have so far:

var margin = {top: 20, right: 20, bottom: 20, left: 20},
    width = 400 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

var xScale = d3.scale.ordinal()
    //.domain(???help???)
    .rangeRoundBands([0, width], .3);

var yScale = d3.scale.linear()
    //.domain(???help???)
    .range([height, 0]);

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

var yAxis = d3.svg.axis()
    .scale(yScale)
    .orient("left")
    .ticks(5);

var svg = d3.select("body").selectAll("svg")
    .data(data)
    .enter()
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .attr("id", function(d){return d.category})
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis)
    .selectAll("text")  
        .style("text-anchor", "end")
        .attr("transform", function(d) {
            return "rotate(-25)" 
        });

svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

var subcategory = svg.selectAll(".subcategory")
    .data(function(d){ return d3.values(d.subcategories);})
    .enter()
    .append("g")
    .attr("class", "subcategory")
    .attr("id", function(d){return d.subcategory;});

var comment = subcategory.selectAll(".comment")
    .data(function(d){return d3.values(d.comments);})
    .enter()
    .append("g")
    .attr("class", "comment")
    .attr("id", function(d){return d.comment;});

comment.append("rect")
    .attr("height", function(d){
      return height - yScale(d.count);
    })
    .attr("width", xScale.rangeBand()/2)
    .attr("y", function(d){
      return yScale(d.count);
    });

comment.append("text")
    .text(function(d){ 
        return d.count; 
    })
    .attr("x", xScale.rangeBand() / 2)
    .attr("y", function(d){ 
        return yScale(d.count) - 5;
    })
    .attr("text-anchor", "middle")
    .attr("fill", "#353535")
    .attr("font-weight", "bold");

This, of course, makes the axes and the width, height, x, and y attributes on the rectangle and text elements go all crazy. This is following a basic bar chart template that I've used several times and always works fine when I only have 1 xscale domain and 1 yscale domain.

So how do I set the xScale domain? And yScale domain? How do I grab each comment out of a Category and say "these will be the xScale for this chart"? Remember, some of the charts will have 30 comments, some will have 7 comments, some will have a max comment count of 200 some will have a max comment count of 2. They are variable for each chart. So if I'm using d3 to create an SVG element for each category in the data array, how do I solve this?

like image 507
rowyourboat Avatar asked Feb 15 '23 08:02

rowyourboat


2 Answers

The xScale and yScale is going to vary for each category chart, because they have different domains (max value in the case of the y scale). Therefore I'd recommend you create separate ones within an each call as in this fiddle

d3.select("body").selectAll("svg")
    .data(data)
    .enter()
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .attr("id", function(d){return d.category})
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
    .each(function(d, i){
        var svg = d3.select(this); 
        var allComments = d.subcategories.reduce(function(prev, curr, i, array){
             return prev.concat(curr.comments);
        }, []);
        var xDomain = allComments.reduce(function(prev, curr, i, array){
            prev.push(curr.comment);
            return prev;
        }, []);
        var yMax = d3.max(allComments, function(comment) {
          return comment.count;  
        })

        var xScale = d3.scale.ordinal()
            .domain(xDomain)
            .rangeRoundBands([0, width], .3);

        var yScale = d3.scale.linear()
            .domain([0, yMax + 2]) // giving ticks specific padding
            .range([height, 0]);

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

        var yAxis = d3.svg.axis()
        .scale(yScale)
        .orient("left")
        .ticks(5);   


        svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis)
            .selectAll("text")  
                .style("text-anchor", "end")
                .attr("transform", function(d) {
                    return "rotate(-25)" 
                });
....
like image 144
cbayram Avatar answered Feb 17 '23 01:02

cbayram


It sounds like you need to find the range-of-values within your dataset. To accomplish that you can do something like:

// find data range

var yMin = d3.min(data, function(d){ return Math.min(d.comments); });
var yMax = d3.max(data, function(d){ return Math.max(d.comments); });

// or use d3.extent like so
var xDomain = d3.extent(data, function (d, i){ return d.category; });

// scale and add range
var xScale = d3.scale.ordinal()
    .domain(xDomain)
    .range([0, width]);

var yScale = d3.scale.linear()
    .domain([yMin, yMax])
    .range([height - margin.top, margin.bottom]);
like image 42
DeBraid Avatar answered Feb 17 '23 02:02

DeBraid