我第一次使用D3,並且我按照他們的網站上的說明來達到這一點。儘管Chrome中的JS控制檯沒有例外,但似乎無法顯示圖表。D3.js不顯示圖表
這裏的JS在我的網頁的標題:在JSON請求到服務器端腳本
<script>
var margin = {
top: 0,
right: 0,
bottom: 10,
left: 0
},
width = 838 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var chart = d3.select(".day_chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.json("http://solarmonitoringaustralia.com.au/myphp/inverterdata.php?var=TEST1&id=C120031", function (error, data) {
data.forEach(function (d) {
d.hour = +d.hour; // coerce to number
d.max_energy = +d.max_energy;
alert(d.hour + " -- " + d.max_energy);
});
x.domain(data.map(function (d) {
return d.hour;
}));
y.domain([0, d3.max(data, function (d) {
return d.max_energy;
})]);
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
chart.append("g")
.attr("class", "y axis")
.call(yAxis);
chart.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function (d) {
return x(d.hour);
})
.attr("y", function (d) {
return y(d.max_energy);
})
.attr("height", function (d) {
return height - y(d.max_energy);
})
.attr("width", x.rangeBand());
});
</script>
該代碼調用。下面是執行查詢時,它返回到瀏覽器中的數據:
[{"hour":"1","max_energy":"15.969"},{"hour":"2","max_energy":"19.065"},{"hour":"3","max_energy":"21.191"},{"hour":"4","max_energy":"23.151"},{"hour":"5","max_energy":"24.403"},{"hour":"6","max_energy":"25.082"},{"hour":"7","max_energy":"25.494"},{"hour":"8","max_energy":"25.499"},{"hour":"9","max_energy":"4.685"},{"hour":"10","max_energy":"7.309"},{"hour":"11","max_energy":"10.051"},{"hour":"12","max_energy":"13.119"}]
我的HTML包含這個標籤,我想圖表顯示:
<sgv class="day_chart"></svg>
我可以看到在將數據傳遞到JS上方通過data.forEach(函數(d))中的「alert」函數,數據返回。
頁面加載但是它會加載一個空白區域,並且控制檯中沒有JS錯誤。感謝您的任何建議!
這個例子依賴於具有類「day_chart」的元素存在 - 你有嗎? –
嗨拉爾斯,謝謝你的回覆。我已經修改了上面的帖子以包含我的HTML,其中包含以下標記,我希望顯示圖表:就像在示例中一樣。 – TheRealPapa
你可以發佈一個完整的工作示例,演示問題請,最好是像jsfiddle的地方? –