首页 > 解决方案 > 使用 D3.JS 将 HTML 标签添加到轴标签

问题描述

我正在使用 vue 和 d3 制作简单的水平条形图。我想沿垂直轴自定义我的轴标签。现在,我指定在每个标签中放置什么的代码如下所示:

let yAxis = d3.axisLeft()
  .scale(this.yScale)
  .tickSize(0)
  .tickPadding(4)
  .tickFormat((d, i) => { return this.data[i].country + " " + this.data[i].value })

我希望我的标签看起来像这样:

国家 价值
国家1 10.2
国家2 200.3
国家2 3000.4

即国家必须左对齐,而值必须右对齐。此外,值必须以粗体显示。问题在于,似乎 .tickFormat 不接受任何 html 标签

标签: javascripthtmlvue.jsd3.js

解决方案


这是设置轴标签样式的示例:

const svg = d3.select("svg")
    .attr("width", 1000)

// Create the scale
const x = d3.scaleLinear()
    .domain([0, 100])         // This is what is written on the Axis: from 0 to 100
    .range([100, 800]);       // This is where the axis is placed: from 100px to 800px

// Draw the axis
svg
  .append("g")
  .classed('x-axis', true)
  .attr("transform", "translate(0,50)")      // This controls the vertical position of the Axis
  .call(d3.axisBottom(x));
  
svg.select('.x-axis')
  .selectAll('text')
  .style('fill', 'red')
  .style('font-size', '32px')
  .attr('y', 20)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>


推荐阅读