首页 > 解决方案 > D3 - 将 x 值数据刻度显示为百分比

问题描述

有一个如下所示的折线图:https : //imgur.com/1kadiJF 希望 x 轴在每个刻度后显示一个 & 符号,10%、20% 等。如何实现这一点?

我已经阅读了一种可以使用的格式方法,以及看到人们使用数学并实际进行转换,但我认为必须有一种快速的方法来在每个刻度后添加一个字符串 %,当然!

在这里使用 D3 的 V4


    <script>
        // set the dimensions and margins of the graph
        const formatPercent = d3.format(".0%")
        const margin = {top: 20, right: 30, bottom: 60, left: 250},
            width = 1000 - margin.left - margin.right,
            height = 300 - margin.top - margin.bottom;
        
        // append the svg object to the body of the page
        const svg = d3.select(".line")
          .append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
          .append("g")
            .attr("transform",
                  "translate(" + margin.left + "," + margin.top + ")");
        
        // Parse the Data
        d3.json("./data/linedata.json", function(data) {
        
          // Add X axis
          const x = d3.scaleLinear()
            .domain([0, 100])
            .range([ 0, width]);
          svg.append("g")
            .attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x))
            .selectAll("text").attr('class', 'xaxis')
              .attr("transform", "translate(0,0 )")
              
              .style("text-anchor", "end");
        
          // Y axis
          const y = d3.scaleBand()
            .range([ 0, height ])
            .domain(data.map(function(d) { return d.desc; }))
            .padding(.1)
          svg.append("g").attr('class', 'xaxis')
            .call(d3.axisLeft(y))
        
          //Bars
          svg.selectAll("myRect")
            .data(data)
            .enter()
            .append("rect")
            .attr("x", x(0) )
            .attr("y", function(d) { return y(d.desc); })
            .attr("width", function(d) { return x(d.total); })
            .attr("height", y.bandwidth() )
            .attr("fill", "#008080")
        
        })
        
        </script>

标签: javascriptwebd3.js

解决方案


您是否尝试过使用 tickFormat 函数?像这样的东西应该工作:

.tickFormat(d => d + "%")


推荐阅读