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

标签 javascript dom d3.js c3

根据C3 documentation , legend.inset.postition 只支持top-left, top-right, bottom-left右下 位置。我想让我的图例位于 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
        }
    }
});

我试图在图表渲染后通过确定元素的当前位置来重新定位该元素。但是,似乎没有任何 SVG 元素具有支持这种自省(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

最佳答案

难道您不能将插入对象的 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/

关于javascript - 在顶部中心放置一个插图图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30202453/

相关文章:

javascript - 如何制作将 JSON 数据插入 HTML 的 XMLHttpRequest?

javascript - 如何在 Google Gears Worker 中包含 javascript 文件(无 DOM 访问权限)

javascript - 您如何找到起始标记或结束标记的(字符串)长度?

php - 加载时间 : is it quicker to parse HTML with PHP's DOMDocument or with Regular Expressions?

javascript - d3 力链接未连接

javascript - 如何在单击单选按钮时使按钮处于非事件状态?

javascript - 从日期数组中减去 1 个月

javascript - 在 Firefox 上,异步回调在 DOMContentLoaded 之前运行

javascript - d3.select(this) 适用于鼠标悬停,但不适用于鼠标悬停时调用的函数

javascript - 在 SVG 元素上触发点击事件