我现在已经完成了图表。 但是,结果图的值不等于x轴的比例。 有没有办法将图表的值和比例相互同步? 该值已超出,但与x轴的比例不匹配。
[
{"name":"a","energy":200},
{"name":"a","energy":400},
{"name":"a","energy":450},
{"name":"a","energy":300},
{"name":"a","energy":120}
]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>d3_bar chart</title>
<script src="http://d3js.org/d3.v4.js"></script>
</head>
<body>
<svg id="test1" width="250" height="250"></svg>
<script>
var data = d3.json("data_F.json", function (error,data){
alert(data);
alert(error);
//var max = d3.max(data, function(d){return d.energy;})
//var sum = d3.sum(data, function(d){return d.energy;});
//alert(max);
//alert(sum);
var dataTotal = d3.nest()
.key(function(d){return d.name;})
.rollup(function(v){
return d3.sum(v, function(d){return d.energy;});
})
.entries(data);
console.log(JSON.stringify(dataTotal));
var max = d3.max(data, function(d){return d.energy;});
console.log(JSON.stringify(max));
var sum = d3.sum(data, function(d){return d.energy;});
console.log(JSON.stringify(sum));
var width=250,
height=250,
padding=20
maximum=5000; // 그래프백분율최대값
var canvas = d3.select("#test1")
.append("svg")
.attr("width",width)
.attr("height",height);
//var format = d3.format("%");
//var formattedX = format(dataTotal.value);
//alert(formattedX);
var rect = canvas.selectAll("rect")
.data(dataTotal)
.enter()
.append("rect")
.attr("width", function(d){return ((d.value/maximum)*100);})
.attr("height",30)
.attr("x",20)
.attr("y",function(d,i){return i*20;})
.attr("fill","steelblue");
var text = canvas.selectAll("text")
.data(dataTotal)
.enter()
.append("text")
.attr("fill","black")
.attr("x",100)
.attr("y",function(d,i){return i*50+80;})
.text(function(d){return (((d.value/maximum)*100)+"%");});
var xScale = d3.scaleLinear()
.range([padding,230])
.domain([0,100]);
var xAxis = d3.axisBottom()
.scale(xScale)
;
//.tickFormat(function(d){return Math.round(d*100/max)}+"%");
var gX = canvas.append("g")
.attr("transform","translate(0,"+(30)+")")
.call(xAxis);
})
</script>
</body>
</html>
答案 0 :(得分:0)
假设x轴的宽度为400
var x_scale_width=400;
100%的宽度是轴的宽度减去你留下的填充:
var total_width=x_scale_width-padding
;
X%的宽度为total_width*X/100
在您的情况下X=(d.value/maximum)*100;
因此X%的宽度为((x_scale_width)-padding)*(d.value/maximum)