svg矩形不同侧面的标签

时间:2016-04-01 10:05:45

标签: javascript d3.js svg

我想标记我的图表Waterfall_Chart,以便它显示矩形右侧的值(如果它是正数),如果它是负数则显示在左侧。

在代码中的第197-198行,我按照以下方式执行:

label.selectAll("tspan")
    .attr("x", function(d) { 
        return x(d.value1) + (d.value0 < d.value1 ? 5 : -25);
    }); 
    // 5px space from the right of the rect to (positive) label : 
    // -38px space from the lefr of the rect to (negative) label; 

小数字可以正常工作,但是当我有大数字时,标签会与矩形相交。

&#13;
&#13;
var margin = {top: 30, right: 200, bottom: 50, left: 100},
    width = 900 - margin.left - margin.right,
    height = 350 - margin.top - margin.bottom;

var formatChange = d3.format("+d"),
    formatValue = d3.format("d");

var w = width + margin.left + margin.right;
var h = height + margin.top + margin.bottom;

var svg = d3.select("body").append("svg")
	.attr("viewBox", "0 0 " + w + " " + h)
	.attr("preserveAspectRatio", "xMidYMid meet")
  .append("g")
	.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

data = [{id:"name1",val1:23,val2:344224},
		{id:"name2",val1:26544,val2:13222},
		{id:"name3",val1:15433,val2:154324},
		{id:"name4",val1:22453,val2:1654437},
		{id:"name5",val1:23213,val2:154325},
		{id:"name6",val1:254321,val2:22457},
		{id:"name7",val1:22344,val2:32353},
		{id:"name8",val1:13222,val2:245329}];
	

//d3.requestCsv("data_WfH.csv", function(error, data) {

  var values = d3.keys(data[0]).filter(function(key) {
    return key !== "id";});	
  
data.forEach(function(d) {
 for (var i = 0; i < values.length; i++) {
	d.value = +d[values[i]];
  return d;}});

var value1Sum = 0,
    value2Sum = 0;
	
	value1Sum = d3.sum(data, function(d){return d[values[0]];});
    value2Sum = d3.sum(data, function(d){return d[values[1]];});

	data = function (array) {
            r = array.map(function (d) {
                return { id: d.id, value: d[values[1]] - d[values[0]] };
            });
        return [{ id: values[0], value: value1Sum }].concat(r, { id: values[1], value: value2Sum });
    }(data);
	
  data.reduce(function(v, d) { return d.value1 = (d.value0 = v) + d.value; },0);
  
/*---------- Setting Up Dynamic Scales ----------*/
  
  var x = d3.scaleLinear()
                .domain([d3.min(data,function(d){return d.value0;}), d3.max(data, function(d) { return d.value0; })])
                .range([0, width]);
				
  var y = d3.scaleBand()
                .domain(data.map (function(d) { return d.id; }))
                .range([0, height])
				.padding(0.1);

/*---------- Build the Waterfall Diagram's rectangles ----------*/	  
	  
  svg.append("g").selectAll("rect")
    .data(data)
    .enter().append("rect")
	.style("stroke", "gray") // stroke color for all rects
	.style("fill", function(d) {
            if (d.value0 < d.value1 & d.value!==value2Sum) {return "green";} // color rect with positive value in green if condition is true (1)
            else if (d.value0 > d.value1 & d.value!==value2Sum)	{return "red";} // color rect with negative value in red if condition is true (1)
			else {return "gray";} // color rect in gray if both previous conditions are false (0)
			}) 
      .attr("y", function(d) { return y(d.id); })
      .attr("x", function(d) { if (d.value!==value2Sum) {return x(d.value0 < d.value1 ? d.value0 : d.value1); }})
      .attr("width", function(d) { return d.value0 < d.value1 ? x(d.value1) - x(d.value0) : x(d.value0) - x(d.value1); })
      .attr("height", y.bandwidth())
	  
	  //при наводці курсора змінює колір ректів крім першого
      .on ( "mouseover" ,  function ( d , i )  { 
    d3 . select ( this ) 
	.style("fill", function(d) {
            if (d.value0 < d.value1 & d.value!==value2Sum) {return "#84E884";} 
            else if (d.value0 > d.value1 & d.value!==value2Sum)	{return "#FFA8A8";}
			else {return "#E8E8E8";} }); })
	. on ( "mouseout" ,  function ( d , i )  { 
    d3 . select ( this ) 
        .style("fill", function(d) {
            if (d.value0 < d.value1 & d.value!==value2Sum) {return "green";} 
            else if (d.value0 > d.value1 & d.value!==value2Sum)	{return "red";} 
			else {return "gray";} }); });

/*---------- Fill first rect with gray color ----------*/
	  
  d3.select("rect")			  // choose the first rect
	.style("fill", "#A2A2A2")	// color it in gray

 //при наводці курсора змінює колір першого ректа
	. on ( "mouseover" ,  function ( d , i )  { 
    d3 . select ( this ) 
        .style("fill", "#E8E8E8")})
	. on ( "mouseout" ,  function ( d , i )  { 
    d3 . select ( this ) 
        .style("fill", "grey")});
	
		 	
/*---------- First vertical line ----------*/

//var minX =data[0].value;//select first value 

svg.append("g")
   .append("line")
	.style("stroke","gray")
	.attr("x1", x(value1Sum))
	.attr("y1", 2)
	.attr("x2",x(value1Sum))
	.attr("y2", height + 50);

/*---------- Last vertical line ----------*/	
	
//var maxX = d3.sum(data, function(d){if (d.value!==value2Sum) {return d.value;}});

svg.append("g")
    .append("line")
	.style("stroke","gray")
	.attr("x1", x(value2Sum))           
	.attr("y1", 2)
	.attr("x2", x(value2Sum))
	.attr("y2", height + 50);
	
/*---------- Count the change ----------*/	

var change = Math.round(value2Sum-value1Sum);

svg.append("text") // append text
    .style("fill", "black")	// fill the text with the colour black
    .style("font-size", "12px") // size of the text
	.style("stroke", "black")
	.style("position","middle")
	.attr("x", x(change/2+value1Sum)) // set x position of left side of text
    .attr("y", height + 40) // set y position of bottom of text 
    .text(change);
	
/*---------- Left Arrow ----------*/

svg.append("image")
    .attr("xlink:href", "img/ArrowRight.png")
    .attr("x", x(value1Sum)-37)
    .attr("y", height+15)
	.attr("width", 37)
    .attr("height", 37);	
	
/*---------- Right Arrow ----------*/	

svg.append("image")
    .attr("xlink:href", "img/ArrowLeft.png")
    .attr("x", x(value2Sum))
    .attr("y", height+15)
	.attr("width", 37)
    .attr("height", 37);
	
/*---------- Label the diagram ----------*/
	 
  var label = svg.append("g").selectAll("text")
      .data(data)
    .enter().append("text")
	  .attr("class", "label")
      .attr("y", function(d) { return y(d.id) + y.bandwidth(); });

/*---------- Label the first element ----------*/

svg.append("text")
	.style("fill", "black")	// fill the text with the colour black
    .style("font-size", "12px") // size of the text
	.attr("x", x(value1Sum)/2)
    .attr("y", 20)
	.text(function(d) {return Math.round(value1Sum);});
	
/*---------- Label the last element ----------*/

svg.append("text")
	.style("fill", "black")	// fill the text with the colour black
    .style("font-size", "12px") // size of the text
	.attr("x", x(value2Sum)/2)
    .attr("y", height-5)
	.text(function(d) {return Math.round(value2Sum);});	
	  
/*---------- Label the value from the table ----------*/	  
	  
 label.append("tspan")
      .attr("class", "label")
      .attr("dy", "-.3em")
      .text(function(d) { 
	  if (d.value!==value1Sum & d.value!==value2Sum) {
	  return formatChange(d.value1 - d.value0); }});

  label.selectAll("tspan")
      .attr("x", function(d) { return x(d.value1) + (d.value0 < d.value1 ? 5 : -25); }); // 5px space from the right of the rect to (positive) label : -38px space from the lefr of the rect to (negative) label; 

 svg.append("g")	// the following set of svg attributes visualizes Y axis
      .attr("class", "axis axis--y")
      .attr("transform", "translate(" + x(0) + ",0)")
      .call(d3.axisLeft(y).tickSize(2));	// deleted .tickPadding(x(0) + 6) which wrote labels of axis y on the right side of the axis.


//}
//)
;
&#13;
body {
  font: 10px sans-serif;
}


.axis path,
.axis line {
  fill: black; /*with fill: none; the axis line is thin, and without 'color'*/
  stroke: black;
  shape-rendering: crispEdges;
  stroke-width: 4px;
}
.axis text {
    font-family: sans-serif;
    font-size: 12px;
}


.label {
  fill: black;
  font-size: 12px;
}

.label-change {
  font-weight: bold;
}

.label-value {
  fill-opacity: 0.8;
}

.label--negative {
 
}
&#13;
<body>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="//d3js.org/d3.v4.0.0-alpha.9.min.js"></script>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

在计算需要显示的标签长度​​后如何做到这一点。

此处的负值(-7* (d.value1 + "").length) 7是任意数字乘以需要显示的字符串的长度。

label.selectAll("tspan")
      .attr("x", function(d) { 
           return x(d.value1) 
           + (d.value0 < d.value1 ? 5 
              : (-7* (d.value1 + "").length)); 
       })

工作代码here

答案 1 :(得分:1)

您可以使用text-anchor属性来确定文本相对于矩形的显示方式:

  • 如果它应显示在右侧,请将text-anchor设置为start,它将显示为已经显示
  • 如果它应显示在左侧,请将x设置为位于矩形左侧稍微的位置,并将text-anchor设置为end

这是一个例子

label.selectAll("tspan")
    .attr("x", function(d) { 
        var rect = d3.select("#rect-" + d.id); // get the rect
        var rectx = parseInt(rect.attr('x')),  // x position
            rectwidth = parseInt(rect.attr('width')); // width
        if (!rectx) return 0;

        if (d.value0 < d.value1)
            // place the text to the right of the rect
            return rectx + rectwidth + 5;
        else
            // place the text to the left of the rect
            return rectx - 5; 
    })
    .attr("text-anchor", function(d) { 
        return (d.value0 < d.value1) ? "start" : "end";
    });

请注意我set an id on the rects to reference them并避免重新计算值

小提琴https://jsfiddle.net/nikoshr/8yv9dzpc/和片段

var margin = {top: 30, right: 200, bottom: 50, left: 100},
    width = 900 - margin.left - margin.right,
    height = 350 - margin.top - margin.bottom;

var formatChange = d3.format("+d"),
    formatValue = d3.format("d");

var w = width + margin.left + margin.right;
var h = height + margin.top + margin.bottom;

var svg = d3.select("body").append("svg")
	.attr("viewBox", "0 0 " + w + " " + h)
	.attr("preserveAspectRatio", "xMidYMid meet")
  .append("g")
	.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

data = [{id:"name1",val1:23,val2:344224},
		{id:"name2",val1:26544,val2:13222},
		{id:"name3",val1:15433,val2:154324},
		{id:"name4",val1:22453,val2:1654437},
		{id:"name5",val1:23213,val2:154325},
		{id:"name6",val1:254321,val2:22457},
		{id:"name7",val1:22344,val2:32353},
		{id:"name8",val1:13222,val2:245329}];
	

//d3.requestCsv("data_WfH.csv", function(error, data) {

  var values = d3.keys(data[0]).filter(function(key) {
    return key !== "id";});	
  
data.forEach(function(d) {
 for (var i = 0; i < values.length; i++) {
	d.value = +d[values[i]];
  return d;}});

var value1Sum = 0,
    value2Sum = 0;
	
	value1Sum = d3.sum(data, function(d){return d[values[0]];});
    value2Sum = d3.sum(data, function(d){return d[values[1]];});

	data = function (array) {
            r = array.map(function (d) {
                return { id: d.id, value: d[values[1]] - d[values[0]] };
            });
        return [{ id: values[0], value: value1Sum }].concat(r, { id: values[1], value: value2Sum });
    }(data);
	
  data.reduce(function(v, d) { return d.value1 = (d.value0 = v) + d.value; },0);
  
/*---------- Setting Up Dynamic Scales ----------*/
  
  var x = d3.scaleLinear()
                .domain([d3.min(data,function(d){return d.value0;}), d3.max(data, function(d) { return d.value0; })])
                .range([0, width]);
				
  var y = d3.scaleBand()
                .domain(data.map (function(d) { return d.id; }))
                .range([0, height])
				.padding(0.1);

/*---------- Build the Waterfall Diagram's rectangles ----------*/	  
	  
  svg.append("g").selectAll("rect")
    .data(data)
    .enter().append("rect")
  .attr("id", function(d) { return "rect-"+d.id; })
	.style("stroke", "gray") // stroke color for all rects
	.style("fill", function(d) {
            if (d.value0 < d.value1 & d.value!==value2Sum) {return "green";} // color rect with positive value in green if condition is true (1)
            else if (d.value0 > d.value1 & d.value!==value2Sum)	{return "red";} // color rect with negative value in red if condition is true (1)
			else {return "gray";} // color rect in gray if both previous conditions are false (0)
			}) 
      .attr("y", function(d) { return y(d.id); })
      .attr("x", function(d) { if (d.value!==value2Sum) {return x(d.value0 < d.value1 ? d.value0 : d.value1); }})
      .attr("width", function(d) { return d.value0 < d.value1 ? x(d.value1) - x(d.value0) : x(d.value0) - x(d.value1); })
      .attr("height", y.bandwidth())
	  
	  //при наводці курсора змінює колір ректів крім першого
      .on ( "mouseover" ,  function ( d , i )  { 
    d3 . select ( this ) 
	.style("fill", function(d) {
            if (d.value0 < d.value1 & d.value!==value2Sum) {return "#84E884";} 
            else if (d.value0 > d.value1 & d.value!==value2Sum)	{return "#FFA8A8";}
			else {return "#E8E8E8";} }); })
	. on ( "mouseout" ,  function ( d , i )  { 
    d3 . select ( this ) 
        .style("fill", function(d) {
            if (d.value0 < d.value1 & d.value!==value2Sum) {return "green";} 
            else if (d.value0 > d.value1 & d.value!==value2Sum)	{return "red";} 
			else {return "gray";} }); });

/*---------- Fill first rect with gray color ----------*/
	  
  d3.select("rect")			  // choose the first rect
	.style("fill", "#A2A2A2")	// color it in gray

 //при наводці курсора змінює колір першого ректа
	. on ( "mouseover" ,  function ( d , i )  { 
    d3 . select ( this ) 
        .style("fill", "#E8E8E8")})
	. on ( "mouseout" ,  function ( d , i )  { 
    d3 . select ( this ) 
        .style("fill", "grey")});
	
		 	
/*---------- First vertical line ----------*/

//var minX =data[0].value;//select first value 

svg.append("g")
   .append("line")
	.style("stroke","gray")
	.attr("x1", x(value1Sum))
	.attr("y1", 2)
	.attr("x2",x(value1Sum))
	.attr("y2", height + 50);

/*---------- Last vertical line ----------*/	
	
//var maxX = d3.sum(data, function(d){if (d.value!==value2Sum) {return d.value;}});

svg.append("g")
    .append("line")
	.style("stroke","gray")
	.attr("x1", x(value2Sum))           
	.attr("y1", 2)
	.attr("x2", x(value2Sum))
	.attr("y2", height + 50);
	
/*---------- Count the change ----------*/	

var change = Math.round(value2Sum-value1Sum);

svg.append("text") // append text
    .style("fill", "black")	// fill the text with the colour black
    .style("font-size", "12px") // size of the text
	.style("stroke", "black")
	.style("position","middle")
	.attr("x", x(change/2+value1Sum)) // set x position of left side of text
    .attr("y", height + 40) // set y position of bottom of text 
    .text(change);
	
/*---------- Left Arrow ----------*/

svg.append("image")
    .attr("xlink:href", "img/ArrowRight.png")
    .attr("x", x(value1Sum)-37)
    .attr("y", height+15)
	.attr("width", 37)
    .attr("height", 37);	
	
/*---------- Right Arrow ----------*/	

svg.append("image")
    .attr("xlink:href", "img/ArrowLeft.png")
    .attr("x", x(value2Sum))
    .attr("y", height+15)
	.attr("width", 37)
    .attr("height", 37);
	
/*---------- Label the diagram ----------*/
	 
  var label = svg.append("g").selectAll("text")
      .data(data)
    .enter().append("text")
	  .attr("class", "label")
      .attr("y", function(d) { return y(d.id) + y.bandwidth(); });

/*---------- Label the first element ----------*/

svg.append("text")
	.style("fill", "black")	// fill the text with the colour black
    .style("font-size", "12px") // size of the text
	.attr("x", x(value1Sum)/2)
    .attr("y", 20)
	.text(function(d) {return Math.round(value1Sum);});
	
/*---------- Label the last element ----------*/

svg.append("text")
	.style("fill", "black")	// fill the text with the colour black
    .style("font-size", "12px") // size of the text
	.attr("x", x(value2Sum)/2)
    .attr("y", height-5)
	.text(function(d) {return Math.round(value2Sum);});	
	  
/*---------- Label the value from the table ----------*/	  
	  
 label.append("tspan")
      .attr("class", "label")
      .attr("dy", "-.3em")
      .text(function(d) { 
	  if (d.value!==value1Sum & d.value!==value2Sum) {
	  return formatChange(d.value1 - d.value0); }});

  label.selectAll("tspan")
      .attr("x", function(d) { 
        var rect = d3.select("#rect-" + d.id);
        var rectx = parseInt(rect.attr('x')), 
        	rectwidth = parseInt(rect.attr('width'));
        if (!rectx) return 0;
        if (d.value0 < d.value1)
        	return rectx + rectwidth + 5;
        else
        	return rectx - 5;
      })
      .attr("text-anchor", function(d) { 
      		return (d.value0 < d.value1) ? "start" : "end";
      });

 svg.append("g")	// the following set of svg attributes visualizes Y axis
      .attr("class", "axis axis--y")
      .attr("transform", "translate(" + x(0) + ",0)")
      .call(d3.axisLeft(y).tickSize(2));	// deleted .tickPadding(x(0) + 6) which wrote labels of axis y on the right side of the axis.


//}
//)
;
body {
  font: 10px sans-serif;
}


.axis path,
.axis line {
  fill: black; /*with fill: none; the axis line is thin, and without 'color'*/
  stroke: black;
  shape-rendering: crispEdges;
  stroke-width: 4px;
}
.axis text {
    font-family: sans-serif;
    font-size: 12px;
}


.label {
  fill: black;
  font-size: 12px;
}

.label-change {
  font-weight: bold;
}

.label-value {
  fill-opacity: 0.8;
}

.label--negative {
 
}
<body>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="//d3js.org/d3.v4.0.0-alpha.9.min.js"></script>