我正在尝试在y轴上绘制一个值为'IV'的简单折线图,并在x轴上绘制'Time'。我从MySQL数据库中读取这些值。这是我正在使用的PHP代码:
<?php
$username = "root";
$password = "root";
$host = "localhost";
$database="db";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "SELECT data.IV, data.Time FROM data";
$query = mysql_query($myquery);
if ( ! $myquery ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
以下是生成的JSON:
[{"IV":"230.8","Time":"15:01:17+22\r"},{"IV":"233.7","Time":"15:06:57+22\r"},{"IV":"230.8","Time":"15:36:25+22\r"},{"IV":"234.5","Time":"15:40:38+22\r"},{"IV":"238.7","Time":"15:41:39+22\r"},{"IV":"238.7","Time":"15:41:50+22\r"},{"IV":"238.7","Time":"15:43:05+22\r"},{"IV":"230.8","Time":"15:01:17+22"},{"IV":"223.8","Time":"15:52:17+22"}]
所以我修改了我在网上找到的例子来尝试渲染数据。但是我得到的只是一个空白页面。这是我的代码,有人可以告诉我,我做错了什么?我已经坚持了几天。
<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */
body { font: 12px Arial;}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
</style>
<body>
<!-- load the d3.js library -->
<script type="text/javascript" src="d3/d3.v3.js"></script>
<script>
// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d.IV); })
.y(function(d) { return y(d.Time); });
// Adds the svg canvas
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Get the data
d3.json("gj.php", function(error, data) {
data.forEach(function(d) {
d.IV = +d.IV;
d.Time = +d.Time;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.IV; }));
y.domain([0, d3.max(data, function(d) { return d.Time; })]);
// Add the valueline path.
svg.append("path") // Add the valueline path.
.attr("class", "line")
.attr("d", valueline(data));
// Add the X Axis
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Add the Y Axis
svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
});
</script>
</body>
以下是我可以看到的截图:
我怀疑问题是在时间结束时存在+(数字)\ r \ n。但是,我需要使用这种格式的数据。
答案 0 :(得分:0)
如果在尝试将时间强制转换为数字后对数据阵列执行console.log,则会看到每个对象上的Time属性为NaN,这会阻止其呈现。查看d3的时间格式化函数,在转换为数字之前将数字字符串解析为实际的javascript日期对象。