2016-11-11 64 views
1

以下腳本創建帶有三個標籤和標題的點刻度軸。正文css選擇器定義正文中所有文本元素的font-family和font-size。雖然軸標題受CSS規則的影響,但軸標記標籤不是,儘管它們本身就是文本元素。我知道我可以使用.axis文本選擇器設置刻度標籤樣式。也許我在這裏忽略了一些明顯的東西,但是阻止用體選擇器呈現刻度標籤?d3.js中的軸刻度標籤的樣式

下面的代碼:

<!doctype html> 
<meta charset="utf-8"> 

<script src="d3.min.V4.js"></script> 

<style> 

body { 
    font-family: Courier; 
    font-size: 18px; 
} 

</style> 

<body> 

</body> 

<script> 

var margin = {top: 20, right: 60, bottom: 40, left: 70}, 
    width = 600, 
    height = 100; 

var svg = d3.select('body').append('svg') 
         .attr('width', width) 
         .attr('height', height); 

var xScale = d3.scalePoint().domain(["blue", "red", "green"]).range([margin.left, width-margin.right]); 

// Add the x Axis 
svg.append("g") 
    .attr("transform", "translate(0," + (height - margin.bottom) + ")") 
    .attr("class", "axis") 
    .call(d3.axisBottom(xScale) 
    ); 

//x axis title 
svg.append('text') 
    .text('Colors') 
    .attr('x', width/2) 
    .attr('y', height - 5) 
    .style("text-anchor", "middle"); 


</script> 

回答

1

根據該API,軸發生器自動設置font-size和在容器g元件蜱的字體家庭,這是默認的樣式(代碼從API的例子複製):

//styles applied to the outer g element: 
<g fill="none" font-size="10" font-family="sans-serif" text-anchor="middle"> 
    <path class="domain" stroke="#000" d="M0.5,6V0.5H880.5V6"></path> 
    <g class="tick" opacity="1" transform="translate(0,0)"> 
     <line stroke="#000" y2="6" x1="0.5" x2="0.5"></line> 
     <text fill="#000" y="9" x="0.5" dy="0.71em">0.0</text> 
    </g> 
    //etc... 
</g> 

因此,似乎由於特異性和優先規則,這種風格壓倒你body CSS樣式。

要更改刻度,您必須在CSS中指定text(或使用類或ID)。

+0

謝謝,但這並沒有解決我的問題。軸標題'顏色'也是一個SVG文本,但它受CSS身體選擇器的影響。 – spyrostheodoridis

+1

是的,你是對的。通過源代碼總是很好的做法! – spyrostheodoridis

0

正如Gerardo提到的那樣,API將使用fill#000作爲默認值繪製。 解決方法是重新選擇文本並對其進行重新設計。 看起來像這樣:

var xScale = d3.scalePoint().domain(["blue", "red", "green"]).range([margin.left, width-margin.right]); 

// Add the x Axis 
var xTicks = svg.append("g") 
    .attr("transform", "translate(0," + (height - margin.bottom) + ")") 
    .attr("class", "axis") 
    .call(d3.axisBottom(xScale) 
    ); 

xTicks.selectAll('text').attr('fill', function(d){ 
    return d; 
    });