简体   繁体   中英

create a dot chart with d3.js showing stacked dots

I'd like to create a dot chart in d3.js, where it looks kind of like a bar chart, but there are stacked dots instead of bars.

This question is similar to what I want: D3.js (Wilkinson type) Dot Plot Example

I've used that code to try and accomplish what I want, but I'm stuck.

Here is an image showing what I want, based on the data for apples in my CSV file: 点图表样机

The code I have so far is below. When I console.log d3.range(d.apples), I see that I have an array for each day, which is what I want. However I can't figure out how to draw a circle for each spot in the array, where the x axis value would be the day # and the y axis value would be the position in the array + 1.

Any help very welcome! Thank you.

Code:

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

    body {
      font: 10px sans-serif;
    }

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

    .dot {
      stroke: none;
    }

    </style>
    <body>
    <script src="//d3js.org/d3.v3.min.js"></script>
    <script>

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

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

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

    var color = d3.scale.category10();

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

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

    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 chart = svg.append("g")
        .attr("id", "chart");


    d3.csv("fruit.csv", function(error, data) {
      if (error) throw error;
        // console.log("data: ", data);

      data.forEach(function(d) {
        d.day = +d.day;
        d.apples = +d.apples;
      });

      x.domain([0,4]);
      y.domain([0,6]);

      svg.append("g")
          .attr("class", "x axis")
          .attr("transform", "translate(0," + height + ")")
          .call(xAxis)
        .append("text")
          .attr("class", "label")
          .attr("x", width)
          .attr("y", -6)
          .style("text-anchor", "end")
          .text("Day");

      svg.append("g")
          .attr("class", "y axis")
          .call(yAxis)
        .append("text")
          .attr("class", "label")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .style("text-anchor", "end")
          .text("amount")

      chart.selectAll("g")
          .data(data)
                .enter()
                .append("g")
                .selectAll("circle")
                .data(data)
            .enter().append("circle")
          .attr("class", "dot")
          .attr("r", 3.5)
          .attr("cx", function(d, i) { return x(d.day); })

                //.attr("cy", function(d,i){ return y(d.apples); })

                .attr("cy", function(d,i,j){ 

                    var range = d3.range(d.apples);
                    console.log("apple range: ", range);

                    return y(range[i])
                })          
          .style("fill", "blue")
          .style("opacity", .5);

    });

    </script>

Data (fruit.csv):

"day","apples"
1,3
2,6
3,1
4,2

There are several ways to do what you want. I believe the most traditional approach is nesting the data and appending several groups, one for each fruit. But, for the sake of simplicity, I'd like to propose a different approach: let's change your data, flattening it, so, in each object, we have only one fruit:

originalData.forEach(function(d) {
    data.push({
        day: d.day,
        fruit: "apples",
        amount: +d.apples
    });
    data.push({
        day: d.day,
        fruit: "pears",
        amount: +d.pears
    });
    data.push({
        day: d.day,
        fruit: "oranges",
        amount: +d.oranges
    });
});

Where originalData is the data array the way it is right now.

Doing that, your data will become something like this:

[{
    "day": "1",
    "fruit": "apples",
    "amount": 3
}, {
    "day": "1",
    "fruit": "pears",
    "amount": 6
}, {
    "day": "1",
    "fruit": "oranges",
    "amount": 3
}, {
    "day": "2",
    "fruit": "apples",
    "amount": 6
},//etc...
]

Then, we set a ordinal scale for the days:

var x = d3.scale.ordinal()
    .rangePoints([0, width], 0.5);
    .domain(data.map(d => d.day));

And, finally, we paint the circles:

var dots = svg.selectAll("circle")
    .data(data)
    .enter().append("circle")
    .attr("class", "dot")
    .attr("r", 3.5)
    .attr("cx", function(d) {
        return x(d.day);
    })
    .attr("cy", function(d) {
        return y(d.amount)
    })
    .style("fill", function(d) {
        return color(d.fruit)
    })
    .style("opacity", .5);

Here is a demo (I put some titles, so you can hover over the dot to check the fruit and the amount):

 var rawData = d3.csv.parse(d3.select("#csv").text()); var data = []; rawData.forEach(function(d) { data.push({ day: d.day, fruit: "apples", amount: +d.apples }); data.push({ day: d.day, fruit: "pears", amount: +d.pears }); data.push({ day: d.day, fruit: "oranges", amount: +d.oranges }); }); var margin = { top: 30, right: 20, bottom: 30, left: 50 }, width = 360 - margin.left - margin.right, height = 300 - margin.top - margin.bottom; var x = d3.scale.ordinal() .rangePoints([0, width], 0.5); var y = d3.scale.linear() .range([height, 0]); var color = d3.scale.category10() .domain(["apples", "pears", "oranges"]); var xAxis = d3.svg.axis() .scale(x) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left"); 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 chart = svg.append("g") .attr("id", "chart"); x.domain(data.map(d => d.day)); y.domain([0, 10]); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis) .append("text") .attr("class", "label") .attr("x", width) .attr("y", -6) .style("text-anchor", "end") .text("Day"); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("class", "label") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text("amount"); var dots = svg.selectAll("circle") .data(data) .enter().append("circle") .attr("class", "dot") .attr("r", 3.5) .attr("cx", function(d) { return x(d.day); }) .attr("cy", function(d) { return y(d.amount) }) .style("fill", function(d) { return color(d.fruit) }) .style("opacity", .5) .append("title") .text(function(d){ return d.fruit + ": " + d.amount}); 
 pre { display: none; } body { font: 10 px sans - serif; } .axis path, .axis line { fill: none; stroke: #999; shape-rendering: crispEdges; } .dot { stroke: none; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> <pre id="csv">"day","apples","pears","oranges" 1,3,6,3 2,6,8,2 3,1,0,7 4,2,3,8</pre> 


EDIT : After further clarifications in the comments, this is what OP wants:

Append the groups as you did, but translating them according to the day:

var groups = svg.selectAll(".groups")
    .data(data)
    .enter()
    .append("g")
    .attr("transform", function(d) {
        return "translate(" + x(d.day) + ".0)";
    });

And, in the dots, set the data using d3.range :

var dots = groups.selectAll("circle")
    .data(function(d){ return d3.range(+d.apples + 1)})

That way, for each group, the data for the circles goes all the way up to the maximum. For example, if in a given day "apples" is 3, the data will be:

[0, 1, 2, 3]

Or, if "apples" is 6, the data will be:

[0, 1, 2, 3, 4, 5, 6]

If you don't want the leading zero, just do d3.range(1, +d.apples + 1) .

Here is a demo:

 var data = d3.csv.parse(d3.select("#csv").text()); var margin = { top: 30, right: 20, bottom: 30, left: 50 }, width = 360 - margin.left - margin.right, height = 300 - margin.top - margin.bottom; var x = d3.scale.ordinal() .rangePoints([0, width], 0.5); 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"); 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 chart = svg.append("g") .attr("id", "chart"); x.domain(data.map(d => d.day)); y.domain([0, 7]); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis) .append("text") .attr("class", "label") .attr("x", width) .attr("y", -6) .style("text-anchor", "end") .text("Day"); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("class", "label") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text("amount"); var groups = svg.selectAll(".groups") .data(data) .enter() .append("g") .attr("transform", function(d) { return "translate(" + x(d.day) + ".0)"; }); var dots = groups.selectAll("circle") .data(function(d) { return d3.range(1, +d.apples + 1) }) .enter().append("circle") .attr("class", "dot") .attr("r", 3.5) .attr("cy", function(d) { return y(d) }) .style("fill", "blue") .style("opacity", .5); 
 pre { display: none; } body { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #999; shape-rendering: crispEdges; } .dot { stroke: none; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> <pre id="csv">"day","apples" 1,3 2,6 3,1 4,2</pre> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM