2015-04-21 134 views
0

我在d3.js中有一个水平条形图,我想为图表的每个条形图添加名称,如“y-label”。水平条形图d3.js不显示标签

我的条形图的原始示例是http://bl.ocks.org/mbostock/2368837 没有负值。 所以我修改为我的目的

var margin = {top: 40, right: 20, bottom: 100, left: 60}, 
width = 720 - margin.left - margin.right, 
height = 480 - margin.top - margin.bottom; 

var x_4 = d3.scale.linear() 
    .range([0, width]) 

var y_4 = d3.scale.ordinal() 
    .rangeRoundBands([0, height], .2); 

var xAxis_4 = d3.svg.axis() 
    .scale(x_4) 
    .orient("top"); 

var tip_4 = d3.tip() 
.attr('class', 'd3-tip') 
.offset([-10, 0]) 
.html(function(d) { 
    return "<strong>Value:</strong> <span style='color:red'>" + d.ln_numfollowers + "</span>"; 
}) 

var sampleSVG_4 = d3.select("#LinkedIn").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 + ")") 
    .call(tip_4); 

d3.csv("@routes.Assets.at("d3/linkedin_competitor_prova.csv")", type, function(error, data) { 
    x_4.domain(d3.extent(data, function(d) { return d.ln_numfollowers; })).nice(); 
    y_4.domain(data.map(function(d) { return d.organization_name; })); 

    sampleSVG_4.selectAll(".bar") 
     .data(data) 
    .enter().append("rect") 
     .attr("class", function(d) { return d.ln_numfollowers < 0 ? "bar negative" : "bar positive"; }) 
     .attr("x", function(d) { return x_4(Math.min(0, d.ln_numfollowers)); }) 
     .attr("y", function(d) { return y_4(d.organization_name); }) 
     .attr("width", function(d) { return Math.abs(x_4(d.ln_numfollowers) - x_4(0)); }) 
     .attr("height", y_4.rangeBand()) 
     .on('mouseover', tip_4.show) 
     .on('mouseout', tip_4.hide);; 

    sampleSVG_4.append("g") 
     .attr("class", "x axis") 
     .call(xAxis_4); 

    sampleSVG_4.append("g") 
     .attr("class", "y axis") 
    .append("line") 
     .attr("x1", x_4(0)) 
     .attr("x2", x_4(0)) 
     .attr("y2", height) 
}); 

function type(d) { 
    d.ln_numfollowers = +d.ln_numfollowers; 
    return d; 
} 

CSV数据文件是:

ORGANIZATION_NAME,ln_numfollowers

Carrot.mx,100 CarJump,45

我不知道为什么organization_name没有显示。如您所见,即使在原始示例中,y轴上的标签也不会显示。

回答

1

两个问题:

1)你可能不希望使用extent创建您的x轴。使用您的示例数据,这将创建一个从45到100的图表。您可能希望从零开始。

x_4.domain([0,d3.max(data, function(d) { return d.ln_numfollowers; })]); 

2.)实际上并没有创建一个传统的y轴。此代码:

sampleSVG_4.append("g") 
    .attr("class", "y axis") 
    .append("line") 
    .attr("x1", x_4(0)) 
    .attr("x2", x_4(0)) 
    .attr("y2", height) 

正在创建只是一条线的y轴。它不使用内置的d3轴创建。您需要的是:

var yAxis_4 = d3.svg.axis() 
    .scale(y_4) 
    .orient("left"); 

.... 

sampleSVG_4.append("g") 
    .attr("class", "y axis") 
    .call(yAxis_4); 

示例here

+0

谢谢,它解决了我的问题! – Fabio