首页 > 解决方案 > y 轴在 D3 Charts v4 中设置自定义值

问题描述

我需要将 y 轴值显示为 60、120、180...或 200、400、600...

目前我的 y 轴显示为 100、200、300..

我的测试代码 - d3 图形库代码..

HTML

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>

<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>

Javascript

 var y = d3.scaleLinear()
    .domain([0, d3.max(data, function(d) { return +d.n; })])
.domain([0, 100000])
    .range([ height, 0 ]);
  svg.append("g")
    .call(d3.axisLeft(y));

示例代码链接 - https://www.d3-graph-gallery.com/graph/line_several_group.html

标签: javascripthtmld3.js

解决方案


尝试使用 scalePoint 而不是 scaleLinear:

 var width = 800, height = 800;
     var data = [60, 120, 180, 240, 300, 360];

    var svg = d3.select("body")
        .append("svg")
        .attr("width", width)
        .attr("height", height);
     
    var x = d3.scalePoint()
        .domain([60, 120, 180, 240, 300])         // This is what is written on the Axis: from 0 to 100
        .range([50, 400]);       // This is where the axis is placed: from 100 px to 800px

    var y = d3.scalePoint()
        .domain([60, 120, 180, 240, 300]) // This is what is written on the Axis
        .range([50, 400]);  // This is where the axis is placed: from 50 px to 400px

// 绘制轴 svg .append("g") .attr("transform", "translate(0,50)") // 这控制轴的垂直位置 .call(d3.axisBottom(x));


推荐阅读