[英]d3 - draw grid lines at specified locations
如何輕松地在某些位置繪制網格線?
我想在x軸上垂直(0,25,50,100,125,250,500,750,1k,1.5k,2k,3k,4k,5k,6k)畫線。
當使用axis.ticks()時,我無法控制繪制網格線的位置。 我還嘗試使用axis.tickValues()來傳遞指定位置的數組,但它不起作用。
更新 :如果我使用.data(xScale.ticks(15))//FIXME
,則不會在刻度線上方精確繪制線條。
如果我使用.data(xScale.tickValues([0, 25, 50, 100, 125, 250, 500, 750]))
而不是.data(xScale.ticks(15))//FIXME
沒有繪制網格線。
更新2:以下更改對我有用:
//specify where to draw all lines
var lines = [0, 25, 50, 100, 125, 250, 500, 750, 1000, 1500, 2000, 3000, 4000, 5000, 6000];
//use your specified lines as data
.data(lines)
這准確地寫在我的行的指定位置。 您既可以指定繪制所有行的位置,也可以只指定不存在刻度的值,並添加Cyril建議的.innerTickSize(-h)
這是我的代碼( 更新代碼 ):
var w = 400;
var h = 175;
var padding = 30;
// custom scale:
var scale = [0,125,250,500,1000,2000,4000,6000];
var output = [0,50,100,150,200,250,300,350];
//specify where to draw all lines
var lines = [0, 25, 50, 100, 125, 250, 500, 750, 1000, 1500, 2000, 3000, 4000, 5000, 6000];
var xScale = d3.scale.linear()
.domain(scale)
.range(output);
// The axis uses the above scale and the same domain:
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.tickValues(scale)
.tickFormat(d3.format("s"));
var svg = d3.select(element)
.append("svg")
.attr("width", w)
.attr("height", h);
//Create X axis
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate("+padding+"," + (h - padding) + ")")
.call(xAxis);
//drawing grid lines
var bar_height = h - padding;
svg.append("g")
.attr("class", "lines")
.selectAll("line")
//.data(xScale.ticks(15))//FIXME
//use your specified lines as data
.data(lines)
.enter().append("line")
.attr("x1", function(d) { return xScale(d); })
.attr("x2", function(d) { return xScale(d); })
.attr("y1", 0)
.attr("y2", bar_height);
你可以做這樣的事情來繪制網格線只是擴展內部刻度尺寸。
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.tickValues(scale)
.innerTickSize(-h)//for extending the grid line
.tickFormat(d3.format("s"));
在這里工作代碼
編輯
為了隱藏幾個刻度,你可以這樣做:
//define scale and its related domain like this.
var scale = [0,25,50,100, 125,250,500,750,1000,2000,3000,4000,5000,6000];
var output = [0,20, 40, 80, 100,200,300,340,400,500,550,600,650,700];
//define ticks that not be displayed this means ticks will not be drawn for the array.
var scaleTicksNotDisplay = [250, 3000,5000]
使用如下條件定義xaxis tickformat:
// The axis uses the above scale and the same domain:
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.tickValues(scale)
.innerTickSize(-h)
.tickFormat(function(d){
if (scaleTicksNotDisplay.indexOf(d)>=0){
return "";//return blank for ticks inside scaleTicksNotDisplay
} else {
return d3.format("s")(d);
}
});
在這里工作代碼
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.