【问题标题】:D3 stacked bar chart not able to see full x axis lablesD3 堆积条形图无法看到完整的 x 轴标签
【发布时间】:2019-03-15 07:34:35
【问题描述】:

我在 D3 上创建了enter image description herefollowing 堆积条形图。

如你所见,我看不到完整的 x 轴标签,

下面是我的javascript代码

var stackedBarChartData = [{
    key: 'Port Klang',
    'color' : COLOR_REDS,
    values: [
        { x:"Allocated", y: 10}, { x:"Unallocated", y: 21}, { x:"Unallocated Expired", y: 45}, { x:"Expiring within 10 days", y: 76}, { x:"Floating", y: 55}, { x:"Hub Inventory", y: 68},{ x:"Total Inventory", y: 32}
    ]
},{
    key: 'Jebel Ali',
    'color' : COLOR_ORANGES,
    values: [
        { x:"Allocated", y: 33}, { x:"Unallocated", y: 76}, { x:"Unallocated Expired", y: 82}, { x:"Expiring within 10 days", y: 67}, { x:"Floating", y: 61}, { x:"Hub Inventory", y: 44},{ x:"Total Inventory", y: 15}

    ]
}];

nv.addGraph({
    generate: function() {
        var stackedBarChart = nv.models.multiBarChart()
            .stacked(true)
            .showControls(false)

        stackedBarChart.yAxis.tickFormat(d3.format(',.0f'));

        var svg = d3.select('#nv-stacked-bar-chartmy')
        .append('svg')
        .datum(stackedBarChartData);
        svg.transition().duration(0).call(stackedBarChart);
        return stackedBarChart;
    }
});

一些标签不可见。如果我增加图表的宽度,那么我可以看到所有的 x 轴标签。但是我不想增加尺寸。还有其他方法可以实现这一目标吗?

【问题讨论】:

  • 嗨,精英。您提供的代码似乎有点不完整。我收到 COLOR_REDS 和 COLOR_ORANGES 未定义的错误。能否请您添加更完整的代码。

标签: javascript jquery d3.js


【解决方案1】:

不幸的是,svg 文本仍然是内联的,需要更复杂的代码才能将文本分成两行。可以在此处找到多线轴标签的示例:https://bl.ocks.org/mbostock/7555321

如果您的轴标签不太长,有两种更简单的替代解决方案:

  1. 减小标签的字体大小。在return stackedBarChart;语句前添加代码:

    var ticks = d3.select('.nv-x').selectAll('.tick'); //select the ticks on the x-axis
    ticks.select('text')
     .style('opacity', '1') //unhide the labels
     .style('font-size', 8); //change the font-size
    
  2. 其他选项是旋转标签。在return stackedBarChart;语句前添加代码:

     svg.attr('height', 400); //increase the height of the svg to make room for the labels
     var ticks = d3.select('.nv-x').selectAll('.tick');
     ticks.selectAll('text')
      .attr('transform', 'translate(-10,10) rotate(-90)') //rotates and shifts the text a bit
      .style('text-anchor', 'end') //sets the text to align to the end
      .style('opacity', 1); //makes all the labels visible
    

您也可以结合使用以上两者。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-22
    • 2019-07-15
    • 2016-10-13
    • 2013-03-31
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多