[英]D3.js - How to use different styles for tick labels in one plot?
我正在使用d3.js來繪制數據。 在x軸上,我的時間在各個范圍內。
因此,刻度標簽看起來像這樣:
我想強調這些年,所以我希望年份標簽大膽,而數月則不會大膽。
我還沒有找到解決方案。 有可能嗎? 如果有,怎么樣?
使用.call
to axis組件創建軸svg節點后,您可以返回並選擇特定的文本節點以更改其樣式。
在這個例子中,我只是檢查哪個軸節點解析為一個數字,這只是年值:
axisNodes.selectAll('text').each(function() {
if(+this.textContent) {
this.classList.add("year");
}
});
然后'year'css類可以應用你想要的任何額外樣式。
//adapted from http://bl.ocks.org/mbostock/4149176 var margin = {top: 250, right: 40, bottom: 250, left: 40}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var x = d3.time.scale() .domain([new Date(2012, 0, 1), new Date(2013, 0, 1)]) .range([0, width]); var xAxis = d3.svg.axis() .scale(x); var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) var axisNodes = svg.append("g") .attr("class", "x axis") .attr("transform", "translate(20,50)") .call(xAxis); axisNodes.selectAll('text').each(function() { if(+this.textContent) { this.classList.add("year"); } });
.axis text { font: 10px sans-serif; } .axis line, .axis path { fill: none; stroke: #000; shape-rendering: crispEdges; } .year { fill: none; stroke: black; shape-rendering: crispEdges; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.