在d3.js中的特定刻度上绘制网格线/刻度线 [英] Draw gridline/tickline at a specific tick in d3.js
问题描述
我正在尝试创建一个散点图,我已经能够做的很好.我想通过在x轴上的特定点和y轴上的特定点绘制刻度线将此图分成四个象限.在我的情况下,两个轴都显示百分比,因此我想在两个轴上的刻度线处画一条线,为0.50,但我不知道如何执行此操作,也找不到任何适用的文档我.
I'm trying to create a scatterplot, which I've been able to do just fine. I'd like to separate this plot into four quadrants by drawing ticklines at a specific point on the x axis and specific point on the y axis. In my case, both axes are showing percentages, so I'd like to draw a line at the tick for 0.50 on both axes, but I haven't any clue how to do this and can't find any documentation that is working for me.
这是我定义轴的方法:
var xAxis = d3.svg.axis()
.scale(x)
.ticks(20)
.tickSubdivide(true)
.tickSize(6, 3, 0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.ticks(20)
.tickSubdivide(true)
.tickSize(6, 3, 0)
.orient("left");
任何见识都会受到赞赏.
Any insight would be appreciated.
推荐答案
此处的关键点是您要尝试添加两条线,以将散点图平均分为四个象限.为此,您可以找到x轴和y轴的最小值/最大值(使用它们相应的比例),然后在中点处添加行:
The key point here is you're trying to append two lines that divide the scatterplot evenly into four quadrants. To do that, you can find the min/max of your x- and y-axes (using their corresponding scales), and then append lines at the midpoint:
var startX = d3.min(x.domain()),
endX = d3.max(x.domain()),
startY = d3.min(y.domain()),
endY = d3.max(y.domain());
var lines = [{x1: startX, x2: endX, y1: (startY + endY)/2, y2: (startY + endY)/2},
{x1: (startX + endX)/2, x2: (startX + endX)/2, y1: startY, y2: endY}]
然后,您只需要在图中添加以下几行即可:
Then you just need to append these lines to your figure:
fig.selectAll(".grid-line")
.data(lines).enter()
.append("line")
.attr("x1", function(d){ return x(d.x1); })
.attr("x2", function(d){ return x(d.x2); })
.attr("y1", function(d){ return y(d.y1); })
.attr("y2", function(d){ return y(d.y2); })
.style("stroke", "#000")
.style("stroke-dasharray", (10, 10));
这样做可以为您提供类似的信息(请参阅相应的完整JSFiddle ):
Doing so gives you something like this (see corresponding complete JSFiddle):
这篇关于在d3.js中的特定刻度上绘制网格线/刻度线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!