gpt4 book ai didi

javascript - svg 矩形不同边上的标签

转载 作者:行者123 更新时间:2023-11-29 21:31:22 24 4
gpt4 key购买 nike

我想为我的图表添加标签 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;

它适用于小数字,但当我有大数字时,标签与矩形相交。

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.


//}
//)
;
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>

最佳答案

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

  • 如果它应该显示在右边,将text-anchor设置为start,它就会显示在右边
  • 如果它应该显示在左边,设置x到rect稍微偏左的位置,设置text-anchorend

举个例子

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并避免重新计算值

fiddle 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>

关于javascript - svg 矩形不同边上的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36353495/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com