调整 D3.js 中刻度的刻度长度和笔划粗细

问题描述 投票:0回答:1

我有兴趣更改 d3 中的刻度,因此有些刻度没有其他刻度那么长。 与标尺类似,我只希望标记整数,并且希望缩短代表小数的刻度。

这是我正在寻求在 Illustrator 中完成的效果的模型。

这是迄今为止我的代码,它允许我仅标记整数。 tickSize工具似乎不支持变量。

var yAxis = d3.axisRight(y)
    .ticks(10)
    .tickSize(30)
    .tickFormat(function (d) {
        return d % 1 === 0 ? d + "°C" : "";
    });

另外,我不知道如何使刻度线的笔划粗细更粗。

javascript d3.js visualization
1个回答
0
投票

我根据您提供的插图创建了示例。我已经包含了所有可定制的选项,可以根据您的需求定制工作。

// Sample data
var data = d3.range(0, 10.5, 0.1); // Example data from 0 to 10 with 0.1 increments

// Set up the dimensions for the SVG container
var width = 500;
var height = 400;
var margin = { top: 20, right: 40, bottom: 20, left: 20 };
var svg = d3.select("body")
            .append("svg")
            .attr("width", width)
            .attr("height", height);

// Define the scale
var yScale = d3.scaleLinear()
               .domain([0, 10]) // Example domain
               .range([margin.top, height - margin.bottom]);

// Define the axis
var yAxis = d3.axisRight(yScale)
              .tickValues(d3.range(0, 11, 0.5)); // Show only integer ticks

// Customize the tick marks
yAxis.tickFormat(function(d) {
    if (d % 1 !== 0) {
        // to show decimal ticks
        //return d.toFixed(1); // Shorten decimal ticks
    } else {
        return d; // Keep integer ticks as they are
    }
});

// Append the axis to the SVG
svg.append("g")
   .attr("transform", "translate(" + (width - margin.right) + ",0)")
   .call(yAxis)
   .selectAll("line")
   .attr("x2", function(d) { return d % 1 !== 0 ? 5 : 10; }) // Customize tick lengths
   .attr("stroke-width", function(d) { return d % 1 !== 0 ? 1 : 1.5; }); // Customize tick thickness
   

svg.selectAll(".tick text")
   .attr("x",15)
   .attr("font-size",15)
   .attr("font-weight","bold")
.axis line {
    stroke: black;
}
.axis text {
    font-size: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"></script>

© www.soinside.com 2019 - 2024. All rights reserved.