从图像中可以看出我正在使用月度数据。 我正试图找到一种方法来显示每个刻度线,但只显示4月份的标签。 例如:2014年4月,2015年4月,2016年4月和2017年4月 - 并在两者之间保留刻度线。 提前致谢。
从此代码生成的X轴
g.append("g") .attr("class", "axis axis--x") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x).ticks(d3.timeMonth.every(1)) .tickFormat(d3.timeFormat("%b %Y") ) ); g.select('.axis.axis--x') .selectAll("text") .style("text-anchor", "end") .attr("dx", "-.8em") .attr("dy", ".15em") .attr("transform", "rotate(-65)" );感谢Sira,这就是我最终的结果:
g.append("g") .attr("class", "axis axis--x") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x).ticks(d3.timeMonth.every(1)) .tickFormat(d3.timeFormat("%b %Y") ) ); g.select('.axis.axis--x') .selectAll("text") .style("text-anchor", "end") .style("opacity", function(d){ if (d3.select(this).text().includes("Apr")){return "1"}else{return "0"} }) .attr("dx", "-.8em") .attr("dy", ".15em") .attr("transform", "rotate(-65)" );As you can see from the image I'm using monthly data. I'm trying to find a way to display every tick mark, but only the April month labels. example: Apr 2014, Apr 2015, Apr 2016 and Apr 2017 - and keep the tick marks in between. Thanks in advance.
X axis generated from this code
g.append("g") .attr("class", "axis axis--x") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x).ticks(d3.timeMonth.every(1)) .tickFormat(d3.timeFormat("%b %Y") ) ); g.select('.axis.axis--x') .selectAll("text") .style("text-anchor", "end") .attr("dx", "-.8em") .attr("dy", ".15em") .attr("transform", "rotate(-65)" );Thanks to Sira, this is what I ended up with:
g.append("g") .attr("class", "axis axis--x") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x).ticks(d3.timeMonth.every(1)) .tickFormat(d3.timeFormat("%b %Y") ) ); g.select('.axis.axis--x') .selectAll("text") .style("text-anchor", "end") .style("opacity", function(d){ if (d3.select(this).text().includes("Apr")){return "1"}else{return "0"} }) .attr("dx", "-.8em") .attr("dy", ".15em") .attr("transform", "rotate(-65)" );最满意答案
看一下d3.class 。 在回调中,您将分别访问基准,索引和this 。
因此,如果您希望仅在数据中包含“Apr”时显示刻度,您可以执行以下操作:
g.select('.axis.axis--x') .selectAll("text") .style("text-anchor", "end") .attr("display", function(d, i, this) { if (!d.contains("Apr") { return "none"; } }) .attr("dx", "-.8em") .attr("dy", ".15em") .attr("transform", "rotate(-65)" );您可以将if替换为其他语句,这些语句将为您希望它消失的数据点返回"none" 。
Take a look at d3.class with callback. Inside the callback, you will have an access to the datum, index and this respectively.
So if you want the ticks to only show up if it contains "Apr" in the data, you can do something like:
g.select('.axis.axis--x') .selectAll("text") .style("text-anchor", "end") .attr("display", function(d, i, this) { if (!d.contains("Apr") { return "none"; } }) .attr("dx", "-.8em") .attr("dy", ".15em") .attr("transform", "rotate(-65)" );You can replace the if with other statements that will return "none" for the data point that you want it to disappear.
更多推荐
发布评论