我正在尝试绘制一个简单的折线图,y 轴上的值为“IV” ,x 轴上的值为“时间”。我从我的 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>
这是我可以看到的屏幕截图:
我怀疑问题出在时间结束时存在 +(digits)\r 。但是我需要使用这种格式的数据。