Javascript D3条形图不能在所有负值和正值下正常工作
我需要在d3的帮助下创建带有正负值的条形图。图表在正负值的组合下运行良好,但如果我只传递负值或正值,则X轴不会出现在正确的位置。谢谢 })); }Javascript D3条形图不能在所有负值和正值下正常工作,javascript,d3.js,Javascript,D3.js,我需要在d3的帮助下创建带有正负值的条形图。图表在正负值的组合下运行良好,但如果我只传递负值或正值,则X轴不会出现在正确的位置。谢谢 })); } 我已经稍微修改了您的示例,我相信它提供了您想要的解决方案 重要的是在yscale上适当地设置域。这里我检测所有值是+ve还是-ve,并将域设置为-100-0或0-100之间 yScale.domain([-100, 100]) .range([height - margin.top - margin.bottom, 0])
我已经稍微修改了您的示例,我相信它提供了您想要的解决方案 重要的是在
yscale
上适当地设置域。这里我检测所有值是+ve还是-ve,并将域设置为-100-0或0-100之间
yScale.domain([-100, 100])
.range([height - margin.top - margin.bottom, 0])
.nice();
if(min > 0) {
// All positive
yScale.domain([0, 100]);
} else if(max < 0) {
// All negative
yScale.domain([-100, 0]);
}
yScale.domain([-100100])
.范围([height-margin.top-margin.bottom,0])
.nice();
如果(最小值>0){
//都是正面的
域([01100]);
}否则如果(最大值<0){
//全部否定
域([-100,0]);
}
如果你需要扩展域上的最小值/最大值,如果你的值超过+-100%。它工作正常,你认为它应该结合在哪里?嘿@ozil请尝试使用所有正值,如“var data=[[[”自2015年3月10日起,”,“100],“1年”,200];“X轴将消失。你总是想缩放Y轴吗?那就这样做怎么样?实际上我需要零轴动力学,如果只有正值,它必须移到底部,负值,它必须移到顶部。因此,图表使用了所有区域,并且看起来很干净。值来自服务,其范围在(+150到-100)之间。范围应在0-100之间
感谢您的快速响应@lan,但如果我通过“数据=[[“自2015年3月10日起”、-100],“1年”,150]。”条形图超出了图形比例,我还需要零轴动态。@MohitAgrawal:好的-这工作正常吗?或者我还需要回答其他问题吗?如果这是你想要的,或者足以让你完成你所需要的,请随意接受这个答案。否则,如果您详细说明一下,我可以更新/添加注释进行解释。
// Custom function for text wrap
function wrap(text, width) {
text.each(function() {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1, // ems
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > 55) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
// The x-accessor for the path generator; xScale ∘ xValue.
function X(d) {
return xScale(d[0]);
}
function Y0() {
return yScale(0);
}
// The x-accessor for the path generator; yScale ∘ yValue.
function Y(d) {
return yScale(d[1]);
}
chart.margin = function(_) {
if (!arguments.length) return margin;
margin = _;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.x = function(_) {
if (!arguments.length) return xValue;
xValue = _;
return chart;
};
chart.y = function(_) {
if (!arguments.length) return yValue;
yValue = _;
return chart;
};
return chart;
}
yScale.domain([-100, 100])
.range([height - margin.top - margin.bottom, 0])
.nice();
if(min > 0) {
// All positive
yScale.domain([0, 100]);
} else if(max < 0) {
// All negative
yScale.domain([-100, 0]);
}