Skip to content Skip to sidebar Skip to footer

Dimple.js - Add Data Labels To Each Bar Of The Bar Chart

I am using dimple.js, which is based on d3.js. Is it possible to add data labels to each bar of the bar chart mentioned in this example http://dimplejs.org/examples_viewer.html?id=

Solution 1:

Yes, it is very much possible.

In the "Advanced bar labels" section on the Dimple.js website, they show an example of this. Click here to see it.

I used the same technique to add bar labels to the snippet you posted.

Notice: I kept the comments pretty much the same, so that you can understand what is going on the code. Also, I changed the size of the chart for testing purposes.

Try this out:

<divid="chartContainer"><scriptsrc="http://d3js.org/d3.v3.min.js"></script><scriptsrc="http://dimplejs.org/dist/dimple.v1.min.js"></script><scripttype="text/javascript">var svg = dimple.newSvg("#chartContainer", 1100, 600);
    d3.tsv("/example_data.tsv", function(data) {
        var myChart = new dimple.chart(svg, data);
        myChart.setBounds(60, 30, 900, 400)
        var x = myChart.addCategoryAxis("x", "Month");
        x.addOrderRule("Date");
        var y = myChart.addMeasureAxis("y", "Unit Sales");
        var s = myChart.addSeries("Sales", dimple.plot.bar);
        myChart.draw();

        // After drawing we can access the shapes and their associated data// to add labels.
        s.shapes.each(function(d) {

            // Get the shape as a d3 selectionvar shape = d3.select(this),

            // Get the height and width from the scales
            height = myChart.y + myChart.height - y._scale(d.height);
            width = x._scale(d.width);

            // Add a text label for the value
            svg.append("text")

            // Position in the centre of the shape (vertical position is// manually set due to cross-browser problems with baseline)
            .attr("x", parseFloat(shape.attr("x")) + width / 2 - 15)
            .attr("y", parseFloat(shape.attr("y")) - height / 2)

            // Centre align
            .style("text-anchor", "middle")
            .style("font-size", "10px")
            .style("font-family", "sans-serif")

            // Make it a little transparent to tone down the black
            .style("opacity", 0.7)

            // Format the number
            .text(d3.format(",.1f")(d.yValue / 1000) + "k");
        });
    });
  </script>

Hope this helps!

Post a Comment for "Dimple.js - Add Data Labels To Each Bar Of The Bar Chart"