在顶部中心放置一个插图图例

Position an inset legend at the top-center

根据C3 documentationlegend.inset.postition只支持top-lefttop-rightbottom-leftbottom-right位置。我想让我的图例位于 top-center.

这是创建情节的 JS:

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
        }
    }
});

我试图在图表呈现后通过确定元素的当前位置来重新定位该元素。但是,none 的 SVG 元素似乎具有启用这种内省的属性:

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

您是否只需将插入对象的 x 值设置为正确的值以使其在顶部居中?

这将取决于您的图表是否以及您的图例有多宽。因此计算结果为 (ChartWidth - LegendWidth) / 2

图例对象类似于:

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

这是一个粗略的例子:http://jsfiddle.net/jrdsxvys/11/