3

According to the C3 documentation, legend.inset.postition only supports top-left, top-right, bottom-left and bottom-right positions. I would like to have my legend positioned at the top-center.

Here is the JS that creates the plot:

var chart = c3.generate({
    data: {
        columns: [
            ['data1', 100, 200, 50, 300, 200, 50, 250, 100, 200, 400, 50],
            ['data2', 400, 500, 250, null, 300, 50, 200, 450, 300, 300, 100]
        ],
    },
    legend: {
        position: 'inset',
        inset: {
            anchor: 'top-left', // how do I implement 'top-center'?
            x: 40,
            y: 2,
            step: 1
        }
    }
});

I have attempted to re-position the element after the chart has been rendered via figuring out its current position. However, none of the SVG elements appear to have attributes that enable this kind of introspection:

var legend = d3.select(".c3-legend-background");
console.log("style[width]: " + legend.style("width")); // style[width]: auto
console.log("attr[x]: " + legend.attr("x")); // attr[x]: null
console.log("attr[y]: " + legend.attr("y")); // attr[y]: null
Tim McNamara
  • 18,019
  • 4
  • 52
  • 83

1 Answers1

4

Wouldn't you just set the x value of the inset object to the correct value to get it to center across the top?

This would depend on your wide your chart if and how wide your legend is. So the calculation would be (ChartWidth - LegendWidth) / 2.

The legend object is then something like:

legend: {
    position:'inset',
    inset: {
        anchor: 'top-left',
        x: 200 // put the result of your calculation here
    }
}

Here's a rough example: http://jsfiddle.net/jrdsxvys/11/

Sean
  • 14,359
  • 13
  • 74
  • 124
  • Do you have any suggestions for accessing (or calculating) `LegendWidth` when you are calling `generate`? – Tim McNamara May 13 '15 at 21:27
  • I don't think you can get it during `generate`. If your chart is going to be a fixed size, with fixed size labels (and therefore a fixed size legend), you could generate it once, check the width, then do the calc and set the `x` value. Failing that, you would have to drop into `D3` code and get the widths after `generate` is called, and then you can set the values accordingly. – Sean May 14 '15 at 05:53
  • 2
    Here's a fiddle where the position of the legend gets set using D3 after generating the chart: http://jsfiddle.net/jrdsxvys/13/ – Sean May 14 '15 at 06:13
  • Thanks Sean. That's brilliant. – Tim McNamara May 14 '15 at 21:42