简体   繁体   English

数据未从D3图表的JSON绑定

[英]data not bind from json for d3 chart

Hi I am using D3 chart. 嗨,我正在使用D3图表。

i'm using This d3 chart : http://bl.ocks.org/diethardsteiner/3287802 我正在使用此d3图表: http : //bl.ocks.org/diethardsteiner/3287802

In this chart all the data are read from variable. 在此图表中,所有数据均从变量中读取。 I want to read the data from json file. 我想从json文件中读取数据。

I have complete the half of the work. 我已经完成了一半的工作。 I did same to complete the another half of the work but it is not working. 我做了同样的工作来完成另一半的工作,但是没有用。

Pie chart is read data from json. 饼图是从json读取数据。 but the bar chart is not to read data from json. 但条形图不是从json读取数据。

Here I have Created Plunker check this and give some solution. 在这里,我创建了Plunker,并检查并提供一些解决方案。 https://plnkr.co/edit/TaXMsUWuIXe5kv3yzazk?p=preview https://plnkr.co/edit/TaXMsUWuIXe5kv3yzazk?p=preview

here what i tried to read data is not read from json. 在这里,我尝试读取数据的内容不是从json读取的。

I want to run this chart as same as this example: http://bl.ocks.org/diethardsteiner/3287802 我要像本例一样运行此图表: http : //bl.ocks.org/diethardsteiner/3287802

i tried like this 我尝试过这样

d3.json("data1.json", function(datasetBarChart){

debugger;
// set initial group value
var group = "All";

function datasetBarChosen(group) {
    var ds = [];
    for (x in datasetBarChart) {
         if(datasetBarChart[x].group==group){
            ds.push(datasetBarChart[x]);
         } 
        }
    return ds;
}


function dsBarChartBasics() {
debugger;
        var margin = {top: 30, right: 5, bottom: 20, left: 50},
        width = 500 - margin.left - margin.right,
       height = 250 - margin.top - margin.bottom,
        colorBar = d3.scale.category20(),
        barPadding = 1
        ;

        return {
            margin : margin, 
            width : width, 
            height : height, 
            colorBar : colorBar, 
            barPadding : barPadding
        }           
        ;
}

function dsBarChart() {
debugger;
    var firstDatasetBarChart = datasetBarChosen(group);             

    var basics = dsBarChartBasics();

    var margin = basics.margin,
        width = basics.width,
       height = basics.height,
        colorBar = basics.colorBar,
        barPadding = basics.barPadding
        ;

    var     xScale = d3.scale.linear()
                        .domain([0, firstDatasetBarChart.length])
                        .range([0, width])
                        ;

    var yScale = d3.scale.linear()

           .domain([0, d3.max(firstDatasetBarChart, function(d) { return d.measure; })])

           .range([height, 0])
           ;

    //Create SVG element

    var svg = d3.select("#barChart")
            .append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .attr("id","barChartPlot")
            ;

    var plot = svg
            .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
            ;

    plot.selectAll("rect")
           .data(firstDatasetBarChart)
           .enter()
           .append("rect")
            .attr("x", function(d, i) {
                return xScale(i);
            })
           .attr("width", width / firstDatasetBarChart.length - barPadding)   
            .attr("y", function(d) {
                return yScale(d.measure);
            })  
            .attr("height", function(d) {
                return height-yScale(d.measure);
            })
            .attr("fill", "lightgrey")
            ;


    // Add y labels to plot 

    plot.selectAll("text")
    .data(firstDatasetBarChart)
    .enter()
    .append("text")
    .text(function(d) {
            return formatAsInteger(d3.round(d.measure));
    })
    .attr("text-anchor", "middle")

    .attr("x", function(d, i) {
            return (i * (width / firstDatasetBarChart.length)) + ((width / firstDatasetBarChart.length - barPadding) / 2);
    })
    .attr("y", function(d) {
            return yScale(d.measure) + 14;
    })
    .attr("class", "yAxis")


    var xLabels = svg
            .append("g")
            .attr("transform", "translate(" + margin.left + "," + (margin.top + height)  + ")")
            ;
    debugger;
    xLabels.selectAll("text.xAxis")
          .data(firstDatasetBarChart)
          .enter()
          .append("text")
          .text(function(d) { return d.category;})
          .attr("text-anchor", "middle")
            // Set x position to the left edge of each bar plus half the bar width
                           .attr("x", function(d, i) {
                                return (i * (width / firstDatasetBarChart.length)) + ((width / firstDatasetBarChart.length - barPadding) / 2);
                           })
          .attr("y", 15)
          .attr("class", "xAxis")
          //.attr("style", "font-size: 12; font-family: Helvetica, sans-serif")
          ;         

    // Title

    svg.append("text")
        .attr("x", (width + margin.left + margin.right)/2)
        .attr("y", 15)
        .attr("class","title")              
        .attr("text-anchor", "middle")
        .text("Elevator Trips by Material Stream and Destination")
        ;
}

dsBarChart();

 /* ** UPDATE CHART ** */

/* updates bar chart on request */

function updateBarChart(group, colorChosen) {
    debugger;
        var currentDatasetBarChart = datasetBarChosen(group);

        var basics = dsBarChartBasics();

        var margin = basics.margin,
            width = basics.width,
           height = basics.height,
            colorBar = basics.colorBar,
            barPadding = basics.barPadding
            ;

        var     xScale = d3.scale.linear()
            .domain([0, currentDatasetBarChart.length])
            .range([0, width])
            ;


        var yScale = d3.scale.linear()
          .domain([0, d3.max(currentDatasetBarChart, function(d) { return d.measure; })])
          .range([height,0])
          ;

       var svg = d3.select("#barChart svg");

       var plot = d3.select("#barChartPlot")
        .datum(currentDatasetBarChart)
           ;

            /* Note that here we only have to select the elements - no more appending! */
        plot.selectAll("rect")
          .data(currentDatasetBarChart)
          .transition()
            .duration(750)
            .attr("x", function(d, i) {
                return xScale(i);
            })
           .attr("width", width / currentDatasetBarChart.length - barPadding)   
            .attr("y", function(d) {
                return yScale(d.measure);
            })  
            .attr("height", function(d) {
                return height-yScale(d.measure);
            })
            .attr("fill", colorChosen)
            ;

        plot.selectAll("text.yAxis") // target the text element(s) which has a yAxis class defined
            .data(currentDatasetBarChart)
            .transition()
            .duration(750)
           .attr("text-anchor", "middle")
           .attr("x", function(d, i) {
                return (i * (width / currentDatasetBarChart.length)) + ((width / currentDatasetBarChart.length - barPadding) / 2);
           })
           .attr("y", function(d) {
                return yScale(d.measure) + 14;
           })
           .text(function(d) {
                return formatAsInteger(d3.round(d.measure));
           })
           .attr("class", "yAxis")                   
        ;


        svg.selectAll("text.title") // target the text element(s) which has a title class defined
            .attr("x", (width + margin.left + margin.right)/2)
            .attr("y", 15)
            .attr("class","title")              
            .attr("text-anchor", "middle")
            .text(group + "'s Elevator Trips by Material Stream and Destination")
        ;
}
});

Thanks, 谢谢,

You are using wrong d3.json callback signature. 您使用了错误的d3.json回调签名。 The first argument of the callback is an error that occurred, or null if no error occurred, the second argument is the returned data. 回调的第一个参数是发生的错误,如果没有发生错误,则为null ,第二个参数是返回的数据。 So, you should use following: 因此,您应该使用以下命令:

d3.json("data1.json", function(error, data){
  if(error) {
    // handle error
  } else {
    // work with the data array
  }
}

The following code snippet demonstrates the loading of dataset from an external JSON storage. 以下代码段演示了如何从外部JSON存储中加载dataset When data has been loaded it is passed to the dsPieChart function that draws the above mentioned pie chart. 加载数据后,数据将传递到绘制上述饼图的dsPieChart函数。

 d3.select(window).on('load', function() { // Loading data from external JSON source d3.json('https://api.myjson.com/bins/1hewit', function(error, json) { if (error) { throw new Error('An error occurs'); } else { dsPieChart(json); } }); }); // Format options var formatAsPercentage = d3.format("%"), formatAsPercentage1Dec = d3.format(".1%"), formatAsInteger = d3.format(","), fsec = d3.timeFormat("%S s"), fmin = d3.timeFormat("%M m"), fhou = d3.timeFormat("%H h"), fwee = d3.timeFormat("%a"), fdat = d3.timeFormat("%dd"), fmon = d3.timeFormat("%b"); // PIE CHART drawing function dsPieChart(dataset) { var width = 400, height = 400, outerRadius = Math.min(width, height) / 2, innerRadius = outerRadius * .999, innerRadiusFinal = outerRadius * .5, innerRadiusFinal3 = outerRadius * .45, color = d3.scaleOrdinal(d3.schemeCategory20); var vis = d3.select("#pieChart") .append("svg:svg") .data([dataset]) .attr("width", width) .attr("height", height) .append("svg:g") .attr("transform", "translate(" + outerRadius + "," + outerRadius + ")"); var arc = d3.arc() .outerRadius(outerRadius).innerRadius(innerRadius); var arcFinal = d3.arc().innerRadius(innerRadiusFinal).outerRadius(outerRadius); var arcFinal3 = d3.arc().innerRadius(innerRadiusFinal3).outerRadius(outerRadius); var pie = d3.pie() .value(function(d) { return d.measure; }); var arcs = vis.selectAll("g.slice") .data(pie) .enter() .append("svg:g") .attr("class", "slice") .on("mouseover", mouseover) .on("mouseout", mouseout) .on("click", up); arcs.append("svg:path") .attr("fill", function(d, i) { return color(i); }) .attr("d", arc) .append("svg:title") .text(function(d) { return d.data.category + ": " + formatAsPercentage(d.data.measure); }); d3.selectAll("g.slice").selectAll("path").transition() .duration(750) .delay(10) .attr("d", arcFinal); arcs.filter(function(d) { return d.endAngle - d.startAngle > .2; }) .append("svg:text") .attr("dy", ".35em") .attr("text-anchor", "middle") .attr("transform", function(d) { return "translate(" + arcFinal.centroid(d) + ")rotate(" + angle(d) + ")"; }) .text(function(d) { return d.data.category; }); function angle(d) { var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90; return a > 90 ? a - 180 : a; } vis.append("svg:text") .attr("dy", ".35em") .attr("text-anchor", "middle") .text("Revenue Share 2012") .attr("class", "title"); function mouseover() { d3.select(this).select("path").transition() .duration(750) .attr("d", arcFinal3); } function mouseout() { d3.select(this).select("path").transition() .duration(750) .attr("d", arcFinal); } function up(d, i) { updateBarChart(d.data.category, color(i)); updateLineChart(d.data.category, color(i)); } } 
 #pieChart { position: absolute; top: 10px; left: 10px; width: 400px; height: 400px; } .slice { font-size: 12pt; font-family: Verdana; fill: white; font-weight: bold; } .title { font-family: Verdana; font-size: 15px; } 
 <script src="https://d3js.org/d3.v4.min.js"></script> <div id="pieChart"></div> 

See also Bar chart from external JSON file example. 另请参见来自外部JSON文件示例的条形图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM