C3.js 图例重叠

C3.js Legends are overlapping

我正在尝试创建折线图,例如 here,但图例重叠。

JavaScript 我使用的代码:

var chart = c3.generate({
    data: {
        columns: [
            ['Country 1', 6, 5.95, 6.69, 7.47, 3.53, 0.92, 7.21, 4.02, 3.97, 4.18, 4.27],
            ['Country 2', 7.45, 7.31, 8.69, 8.74, 5.7, -6.15, 4.4, 4.67, 3.8, 2.02, 3.04],
            ['Country 3', 3.82, 3.06, 2.56, 4.43, 2.2, 1.23, 2.53, 2.4, 3.53, 2.62, 2.58],
            ['Country 4', 7.58, 8.57, 8.24, 7.54, 4.69, 3.68, 7.62, 6.55, 3.64, 4.02, 4.63],
            ['Country 5', 6.48, 5.78, 6.1, 6.51, 4.27, 1.15, 8.04, 4.57, 5.51, 4.99, 5.1]
        ],
    },
    legend: {
        show: true
    }
});
d3.selectAll("#chart .c3-legend-item").style("font-size","20px"); 

c3 部分基于字体大小进行定位。由于您是在图表呈现后设置字体大小,因此无法将其考虑在内。因此,您最好将字体大小设置为常规 CSS:

.c3-legend-item{
  font-size: 20px;
}

已更新 fiddle

编辑

要在之后设置它,您必须自己 "fix" 所有位置。像这样:

var runW = 24;
d3.selectAll("#chart .c3-legend-item")
    .style("font-size","20px")
  .each(function(d){
    var node = this,
        self = d3.select(this);
    setTimeout(function(){
      self.selectAll('rect').attr('x', runW);
        self.select('text').attr('x', runW + 10);
      runW += node.getBBox().width + 10;
    }, 300);
  });

已更新 fiddle

您可以为此使用自定义图例。 首先,需要在生成函数中关闭默认图例

图例:{ 显示:假 }

然后定义如下函数。它基本上渲染了我们想要显示的自定义图例及其行为。

 //Defines the toggle function.   
function toggle(id) {
        chart.toggle(id);
    }
  //.container is the container of the chart , .chart is the container where our // chart renders. span is used to wrap our custom legends.
    d3.select('.container').insert('div', '.chart').attr('class', 'legend').selectAll('span')
        .data(['data1', 'data2', 'data3'])
      .enter().append('span')
        .attr('data-id', function (id) { return id; })
        .html(function (id) { return id; })
        .each(function (id) {
            d3.select(this).style('background-color', chart.color(id));
        })
        .on('mouseover', function (id) {
            chart.focus(id);
        })
        .on('mouseout', function (id) {
            chart.revert();
        })
        .on('click', function (id) {
//This toggles the animation for selected and not selected 
 $(this).toggleClass("c3-legend-item-hidden")
            chart.toggle(id);
        });

参考链接:http://c3js.org/samples/legend_custom.html https://jsfiddle.net/yasu47b/3fk72ay5/