2013-03-12 2 views
3

이 그래프의 막대 위에 값을 표시하는 방법이 있습니까? TSV에서 값을 가져 왔지만 현재 막대 값을 각 막대 위에 레이블로 표시하는 데 어려움이 있습니다.그래프 막대 위에 값 레이블을 표시하는 방법은 무엇입니까?

:

margin = 
top: 30 
right: 30 
bottom: 40 
left: 60 
width = 960 - margin.left - margin.right 
height = 500 - margin.top - margin.bottom 

formatPercent = d3.format("") 

x = d3.scale.ordinal() 
    .rangeRoundBands([width, 0], .1) 

y = d3.scale.linear() 
    .range([height, 0]) 

xAxis = d3.svg.axis() 
    .scale(x) 
    .orient("bottom") 
    .tickFormat(formatPercent) 

yAxis = d3.svg.axis() 
    .scale(y) 
    .orient("left") 
    .tickFormat(formatPercent) 

svg = d3.select("body").append("svg") 
    .attr("width", width + margin.left + margin.right) 
    .attr("height", height + margin.top + margin.bottom) 
    .append("g") 
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")") 

d3.tsv("/Home/GetTsv/data.tsv", (error, data)-> 

    data.forEach((d)-> 
     d.Total = +d.Total 
    ) 

    x.domain(data.map((d)-> d.Year)) 
    y.domain([0, d3.max(data, (d)-> d.Total)]) 

    svg.append("g") 
     .attr("class", "x axis") 
     .attr("transform", "translate(0," + height + ")") 
     .call(xAxis) 
     .append("text") 
     .attr("y", 30) 
     .attr("x", width/2) 
     .attr("dy", ".71em") 
     .style("text-anchor", "end") 
     .text("Year") 

    svg.append("g") 
     .attr("class", "y axis") 
     .call(yAxis) 
     .append("text") 
     .attr("transform", "rotate(-90)") 
     .attr("y", -60) 
     .attr("x", -(height/2)) 
     .attr("dy", ".71em") 
     .style("text-anchor", "end") 
     .text("Total Activity") 

    svg.selectAll(".bar") 
     .data(data) 
     .enter().append("rect") 
     .attr("class", "bar") 
     .attr("x", (d)-> x(d.Year)) 
     .attr("width", x.rangeBand()) 
     .attr("y", (d)-> y(d.Total)) 
     .attr("height", (d)-> height - y(d.Total)) 

# svg.selectAll("text") 
#  .data(data) 
#  .enter() 
#  .append("text") 
#  .text((d)-> d.Total) 
#  .attr("x", (d, i)-> i * (width/data.length)) 
#  .attr("y", (d)-> height - d) 

) 

이 내 그래프의 모습입니다 : enter image description here

이 그래프를 렌더링 내가 현재 가지고있는 것입니다 :

내가 TSV로 가지고있는 데이터입니다 enter image description here

하지만 막대와 비슷한 레이블을 사용하고 싶습니다.

enter image description here

주석 처리 된 라벨이 막대 위에 표시 값을 만들려고 노력하는 나의 시도되는 코드입니다. 트릭을 할해야 할 텍스트 섹션에이 코드를 붙여 넣기

+0

".attr ("y ", (d) -> height - d)"값을 반환하거나 두 번째 d를 y (d.total)로 변경해야합니까? –

답변

4

:

.attr("text-anchor", "middle") 
.attr("x", function(d, i) { return i * (width/dataset.length) + (width/dataset.length)/2; }) 
.attr("y", function(d) { return height - (d * 10) - 10; }) 

는 -10 분명이 경우 10px의 바에서 약간의 거리를가한다. 또한 다른 숫자는 약간 수정해야합니다. 파일에서 코드를 붙여 넣었으므로 데이터 세트가 없으므로 코드에서 어떻게 보이는지 정확히 알 수 없습니다. 그럴 수 없다면 스크립트를 http://jsfiddle.net/에 붙여 넣을 수 있습니까? 그것이 어떻게 작동하는지 알려주세요!

관련 문제