2

我目前正在使用 D3.js 制作饼图。数据存储在 MSSQL 数据库中,然后使用 PHP 将其转换为 JSON。这是我的代码

<?php
// Server Name
$myServer = "SRVR";

// Database
$myDB = "TestDB";

// If using Windows Authentication, get rid of, "'UID'=>$myUser, 'PWD'=>$myPass, "
// Notice that the latest driver uses sqlsrv rather than mssql
$conn = sqlsrv_connect('Database'=>$myDB));

// Change TestDB.vwTestData to YOURDB.dbo.YOURTABLENAME
$sql = "SELECT col, SUM(num) AS 'value'
        FROM db
        GROUP BY col";

$result = array(); 

do {
    while ($row = sqlsrv_fetch_array($data, SQLSRV_FETCH_ASSOC)){
        $result[] = $row; 
    }
} while ( sqlsrv_next_result($data) );

// This will output in JSON format if you try to hit the page in a browser
echo json_encode($result);

sqlsrv_free_stmt($data);
sqlsrv_close($conn);
?>

这工作正常。我已经对其进行了测试,它以如下方式输出 JSON:

[{"col":null,"value":247.9042254},{"col":"value1","value":16.8151576061},{"col":"value2","value":235.4833175609},{"col":"value3","value":2316.072432028},{"col":"value4","value":8904.4001532729}]

我怎样才能把它放在图表中?这是我的 .js 代码

(function() {
    var width = 960,
        height = 500,
        radius = Math.min(width, height) / 2;

    var color = d3.scale.ordinal()
        .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b"]);

    var arc = d3.svg.arc()
        .outerRadius(radius - 10)
        .innerRadius(0);

    var pie = d3.layout.pie()
        .sort(null)
        .value(function(d) { return // Something goes here I assume });

    var svg = d3.select("body").append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

    d3.json("scripts/graphs/script.php", function(error, data) {
        data.forEach(function(d) {

            // Something needs to go here?

        });

        var g = svg.selectAll(".arc")
            .data(pie(data))
            .enter().append("g")
            .attr("class", "arc");

        g.append("path")
            .attr("d", arc)
            .style("fill", function(d) { return color(d.data.age); });

        g.append("text")
           .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
           .attr("dy", ".35em")
           .style("text-anchor", "middle")
           .text(function(d) { return d.data.age; });

    });
})();

如果有人可以帮助我,那就太好了。谢谢!

4

2 回答 2

2

我想到了。我使用了这段代码并为 JSON 定制了它

https://gist.github.com/enjalot/1203641

这是我得到的

(function() {
    var w = 670,                        //width
    h = 326,                            //height
    r = 150,                            //radius
    color = d3.scale.category20c();     //builtin range of colors

    d3.json("script.php", function (data) {
        var vis = d3.select("body")
            .append("svg:svg")              //create the SVG element inside the <body>
            .data([data])                   //associate our data with the document
                .attr("width", w)           //set the width and height of our visualization (these will be attributes of the <svg> tag
                .attr("height", h)
            .append("svg:g")                //make a group to hold our pie chart
                .attr("transform", "translate(" + r + "," + r + ")")    //move the center of the pie chart from 0, 0 to radius, radius

        var arc = d3.svg.arc()              //this will create <path> elements for us using arc data
            .outerRadius(r);

        var pie = d3.layout.pie()           //this will create arc data for us given a list of values
            .value(function(d) { return d.value; });    //we must tell it out to access the value of each element in our data array

        var arcs = vis.selectAll("g.slice")     //this selects all <g> elements with class slice (there aren't any yet)
            .data(pie)                          //associate the generated pie data (an array of arcs, each having startAngle, endAngle and value properties) 
            .enter()                            //this will create <g> elements for every "extra" data element that should be associated with a selection. The result is creating a <g> for every object in the data array
            .append("svg:g")                //create a group to hold each slice (we will have a <path> and a <text> element associated with each slice)
                .attr("class", "slice");    //allow us to style things in the slices (like text)

        arcs.append("svg:path")
            .attr("fill", function(d, i) { return color(i); } ) //set the color for each slice to be chosen from the color function defined above
            .attr("d", arc);                                    //this creates the actual SVG path using the associated data (pie) with the arc drawing function

        arcs.append("svg:text")                                     //add a label to each slice
            .attr("transform", function(d) {                    //set the label's origin to the center of the arc
                //we have to make sure to set these before calling arc.centroid
                d.innerRadius = 0;
                d.outerRadius = r;
                return "translate(" + arc.centroid(d) + ")";        //this gives us a pair of coordinates like [50, 50]
        })
        .attr("text-anchor", "middle")                          //center the text on it's origin
        .text(function(d, i) { return data[i].col; });        //get the label from our original data array
    })
})();

所以问题是我没有将 JSON 中的键值连接到 JS 中的变量。以下是要更改的行:

var vis = d3.select("<PUT DIV ID HERE>")
.value(function(d) { return d.<PUT NUMBER VALUE KEY NAME HERE>; });
.text(function(d, i) { return data[i].<PUT SLICE CATEGORY HERE>; });
于 2013-06-12T13:43:22.767 回答
0

我不完全确定您的代码有什么问题,但是您可以尝试一些简单的方法,例如:

d3.json("scripts/graphs/script.php", function(error, data) {
    data.forEach(function(d) {
        d.value = +d.value
    });

    var g...

或者,您是否可以只调用 php 脚本并将返回的 json 对象存储在一个变量中,然后将该变量传递给 d3.json?

于 2013-06-11T22:08:02.643 回答