NVD3.js中的轴标签

3

我想知道如何在NVD3.js中修改X轴和Y轴标签字体的大小和属性。

文档似乎没有提供这样的选项。这是否可能?

2个回答

5
在NVD3或D3本身中似乎没有默认属性。
但是我们可以通过将SVG CSS属性直接应用于轴的文本元素来更改字体大小或任何其他属性。这可以通过使用<style>标签或使用d3.select()来完成。
轴文本标签由<text>节点创建。对于两个轴,都有父容器元素,其具有以下类。
nv-x //for x axis <text> nodes
nv-y //for y axis <text> nodes

因此,使用它们来设置文本标签的CSS属性非常容易。
.nv-x text{
  font-size: 20px;
  fill: blue;
}
.nv-y text{
  font-size: 17px;
  fill:red;
}

以下是 NVD3 中提供的其他属性的链接。

http://nvd3-community.github.io/nvd3/examples/documentation.html

以下是D3中SVG轴属性的链接。

https://github.com/mbostock/d3/wiki/SVG-Axes

这些内容不包括有关设置刻度字体大小的信息。
以下是有效的代码示例。

<html>
<head>
 <style>
  #chart svg {
    height: 300px;
  }
  .nv-x text{
    font-size: 20px;
          fill: blue;
  }
        .nv-y text{
    font-size: 17px;
          fill:red;
  }
 </style>
<head>
 <meta charset="utf-8">
 <link rel="stylesheet" href="http://nvd3.org/assets/css/nv.d3.css">
 <script type="text/javascript" src="http://nvd3.org/assets/lib/d3.v2.js"></script>
 <script type="text/javascript" src="http://nvd3.org/assets/lib/fisheye.js"></script>
 <script type="text/javascript" src="http://nvd3.org/assets/js/nv.d3.js"></script>
</head>
<body>
 <div id="chart">
   <svg></svg>
 </div>


 <script>
  var data = function() {
    var sin = [],
     cos = [];

    for (var i = 0; i < 100; i++) {
   sin.push({x: i, y: Math.sin(i/10)});
   cos.push({x: i, y: .5 * Math.cos(i/10)});
    }

    return [
   {
     values: sin,
     key: 'Sine Wave',
     color: '#ff7f0e'
   },
   {
     values: cos,
     key: 'Cosine Wave',
     color: '#2ca02c'
   }
    ];
  };

  nv.addGraph(function() {
    window.chart = nv.models.lineChart()
   .useInteractiveGuideline(true)
   ;

    chart.xAxis
   .axisLabel('Time (ms)')
   .tickFormat(d3.format(',r'))
   ;

    chart.yAxis
   .axisLabel('Voltage (v)')
   .tickFormat(d3.format('.02f'))
   ;
   

    d3.select('#chart svg')
   .datum(data())
   .transition().duration(500)
   .call(chart)
   ;

    nv.utils.windowResize(chart.update);

    return chart;
  });

  
 </script>
</body>
</html>


1
我不相信您可以通过NVD3 Javascript API完成这个任务。NVD3库在CSS中指定了轴线颜色和字体大小等属性。
您应该检查nv.d3.css文件,了解他们如何配置不同的CSS属性。
具体来说,我认为您可以尝试调整以下CSS来实现您的要求:
.nvd3 .nv-axis.nv-x text {
    font-family: ...;
    font-size: ...;
    fill: ...'
}

注意:使用 fill 更改颜色,而不是 color(因为我们正在处理 SVG)。

谢谢。这适用于轴标签(在刻度上)和轴标题。要仅样式化轴标题,必须使用.nvd3 .nv-axis.nv-x text.nv-axislabel - Stéphane Laurent

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接