我正在开发一个在web应用程序中制作动态图表的类。应用程序使用bootstrap框架。
我已经尝试将append更改为"DIV“和其他变体等。
var svg = d3.select("'.$this->ChartDiv.'").append("div")但是图表不会出现在这些页面中。
下面是我的类:
class Chart{
//Public variables:
public $tsvFile;
public $JsonLocation;
public $JS;
public $ChartDiv;
public $Width;
public $Height;
function Set($What, $Value){
$this->$What = $Value;
}
//For json
function BuildJson(){
$DataOut = '
<style>
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<script type=text/javascript">
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%Y").parse;
var x = d3.time.scale()
.range([0, width]);
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 line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
var svg = d3.select("'.$this->ChartDiv.'").append("svg:svg")
.attr("width", '.$this->Width.')
.attr("height", '.$this->Height.')
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.json("'.$this->JsonLocation.'", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.close; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Profit (Millions)");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
});
</script>';
$this->JS = $DataOut;
}
}为了调用这个类,我使用了下面的代码:
$Chart = new Chart();
$Chart->Set("JsonLocation", "json_item.php?item=123");
$Chart->Set("ChartDiv", "#Chart");
$Chart->Set("Width", "450");
$Chart->Set("Height", "700");
$Chart->BuildJson();
echo $Chart->JS;基本上,页面中的所有内容都会打印出来,当我在一个空的php文件中尝试执行此操作时,它会显示图表。
现在,我不明白我做错了什么,所以任何指南都会有所帮助。
发布于 2015-10-07 17:04:54
var svg = d3.select("'.$this->ChartDiv.'").append("svg:svg")找到您的ChartDiv元素,将一个SVG元素附加到该元素,并将该SVG元素的D3表示赋给变量svg。然后使用此svg变量将元素添加到图表中。
当您将...append("svg:svg")替换为...append("div")时,您将把内部内容附加到一个div而不是一个SVG元素,这是没有意义的,因为g和path等只是和SVG容器的有效子容器。
此外,您需要将javascript包装在类似于JQuery的$(document).ready(function() { ... })中,或者确保在输出所有必需的HTML之后输出javascript,以便例如ChartDiv/#Chart已经存在。
https://stackoverflow.com/questions/32987705
复制相似问题