簡體   English   中英

D3,設置最大y軸線數

[英]D3, set a max number of the y-axis lines

我不知道如何將y軸的數量限制為5。正如您所看到的,當前的行數比當前更多。

在此處輸入圖片說明

這是代碼:

 <!DOCTYPE html> <style type="text/css"> .area { fill: url(#temperature-gradient); stroke-width: 05px; } } </style> <svg width="860" height="400"></svg> <script src="https://d3js.org/d3.v4.min.js"></script> <script> var svg = d3.select("svg"), margin = { top: 20, right: 50, bottom: 30, left: 50 }, width = +svg.attr("width") - margin.left - margin.right, height = +svg.attr("height") - margin.top - margin.bottom, g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var parseTime = d3.timeParse("%d-%b-%y"); d3.tsv("data.tsv", function(d) { d.date = parseTime(d.date); d.close = +d.close; return d; }, function(error, data) { if (error) throw error; var area = d3.area() .x(function(d) { return x(d.date); }) .y1(function(d) { return y(d.close); }); var x = d3.scaleTime() .rangeRound([0, width]); var y = d3.scaleLinear() .rangeRound([height, 0]); var line = d3.line() .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.close); }); x.domain(d3.extent(data, function(d) { return d.date; })); y.domain([0, d3.max(data, function(d) { return d.close; })]); area.y0(y(0)); var xAxis = d3.axisBottom(x) .ticks(d3.timeYear); var yAxis = d3.axisRight(y) .tickSize(width); //GRADIENT FILL g.append("linearGradient") .attr("id", "temperature-gradient") .attr("gradientUnits", "userSpaceOnUse") .attr("x1", 0).attr("y1", y(20)) .attr("x2", 0).attr("y2", y(300)) .selectAll("stop") .data([{ offset: "0%", color: "white" }, { offset: "100%", color: "#b3d9ff" } ]) .enter().append("stop") .attr("offset", function(d) { return d.offset; }) .attr("stop-color", function(d) { return d.color; }); //FILL AREA g.append("path") .datum(data) .attr("class", "area") .attr("d", area); //LINE g.append("path") .datum(data) .attr("fill", "none") .attr("stroke", "#80bfff") .attr("stroke-linejoin", "round") .attr("stroke-linecap", "round") .attr("stroke-width", 1.5) .attr("d", line); //X-AXIS SET UP function customXAxis(g) { g.call(xAxis); g.select(".domain").remove(); g.selectAll(".tick line"); g.selectAll(".tick line").attr("stroke", "#cdd7e9"); } //Y-AXIS SET UP function customYAxis(g) { g.call(yAxis); g.select(".domain").remove(); g.selectAll(".tick line").attr("stroke", "#cdd7e9"); g.selectAll(".tick:not(:first-of-type) line").attr("stroke", "#cccccc").attr("stroke-width", 0.5); g.selectAll(".tick text").attr("x", width + 15).attr("dy", -4); } g.append("g") .attr("transform", "translate(0," + height + ")") .call(customXAxis); g.append("g") .call(customYAxis); }); 

如果可能的話,還要再問一個問題,我想知道如何制作,以便至少在y軸上有一條額外的線(在650上有一條額外的線,如果在這條線上只有5條線,則會有更多的線)圖中最高的數字。

您應該在軸上設置刻度線:

axis.ticks(5)

在您的情況下:

var yAxis = d3.axisRight(y)
      .ticks(5)
      .tickSize(width);

您用刻度線設置X軸編號,對於y軸應該相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM