1. 程式人生 > >JavaScript-D3入門三-資料繫結

JavaScript-D3入門三-資料繫結

csv資料繫結

<html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>測試D3_v4.3 資料繫結</title>
    <style>
        .kagula_stroke {
            stroke: black;
            stroke-width: 2px;
            stroke-dasharray: 5 5;
        }
    </style>
    <script src='/d3/d3.min.js'></script>
</head>

<body>
    <svg style="width:100%;height:200px;border:1px lightgray solid;">
    </svg>
</body>
</html>



<script type="text/javascript">
    d3.csv("/data/cities.csv", (error,data) => {
        if (error) {
            console.error(error)
        }
        else {
            //dataViz(data)//最簡單的資料bind例子.
            dataViz2(data);
        }
    });
    //Hint:  d3.json的使用方式同d3.csv一樣.

    function dataViz(incomingData) {
        //在body標籤下新增div.cities物件.
        d3.select("body").selectAll("div.cities")
          .data(incomingData)
          .enter()
          .append("div")
          .attr("class","cities")
          .html(d => d.label);

        //1 An empty selection because there are no <div> elements in <body> with class of “cities”
        //2 Binds the data to your selection
        //3 Defines how to respond when there’s more data than DOM elements in a selection
        //4 Creates an element in the current selection
        //5 Sets the class of each newly created element
        //6 Sets the content of the created <div>
    }

    function demo()
    {
        d3.select("svg")
          .selectAll("rect")
          .data([15, 50, 22, 8, 100, 10])
          .enter()
          .append("rect")
          .attr("width", 10)
          .attr("height", d => d)
          .style("opacity", .25);
    }

    //在demo的基礎上, +位移, recangel加stroke
    function demo2() {
        d3.select("svg")
          .selectAll("rect")
          .data([15, 50, 22, 8, 100, 10])
          .enter()
          .append("rect")
          .attr("width", 10)
          .attr("height", d => d)
          .style("opacity", .25)
          .style("fill", "#FE9922")
          .style("stroke", "#9A8B7A")
          .style("stroke-width", "1px")
          .attr("x", (d, i) => i * 10)
          .attr("y", d => 100 - d);
    }

    //在第一個dataViz基礎上顯示了人口.
    function dataViz2(incomingData) {
        var maxPopulation = d3.max(incomingData, d => parseInt(d.population))
        var yScale = d3.scaleLinear().domain([0,maxPopulation]).range([0,460]);//建立一個domain到range的對映.
        d3.select("svg").attr("style","height: 480px; width: 600px;");
        d3.select("svg")
          .selectAll("rect")
          .data(incomingData)
          .enter()
          .append("rect")
          .attr("width", 50)
          .attr("height", d => yScale(parseInt(d.population)))
          .attr("x", (d,i) => i * 60)
          .attr("y", d => 480 - yScale(parseInt(d.population)))
          .style("fill", "#FE9922")
          .style("stroke", "#9A8B7A")
          .style("stroke-width", "1px")
    }

</script>

json資料繫結

<html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>測試D3_v4.3 資料繫結二</title>
    <style>
        .kagula_stroke {
            stroke: black;
            stroke-width: 2px;
            stroke-dasharray: 5 5;
        }
    </style>
    <script src='/d3/d3.min.js'></script>
</head>

<body>
    <svg style="width:100%;height:200px;border:1px lightgray solid;">
    </svg>
</body>
</html>



<script type="text/javascript">
    d3.json("/data/tweets.json", (error, data) => {
        if (error) {
            console.error(error);
        }
        else {
            dataViz(data.tweets);
        }
    });

    function dataViz(incomingData) {
        //根據key重新分類統計資料
        var nestedTweets = d3.nest()
          .key(d => d.user)
          .entries(incomingData);

        //Creates a new attribute based on the number of tweets
        nestedTweets.forEach(d => {
            d.numTweets = d.values.length;
        })

        //
        var maxTweets = d3.max(nestedTweets, d => d.numTweets);
        var yScale = d3.scaleLinear().domain([0, maxTweets]).range([0, 500]);

        //
        d3.select("svg")
          .selectAll("rect")
          .data(nestedTweets)
          .enter()
          .append("rect")
          .attr("width", 50)
          .attr("height", d => yScale(d.numTweets))
          .attr("x", (d, i) => i * 60)
          .attr("y", d => 500 - yScale(d.numTweets))
          .style("fill", "#FE9922")
          .style("stroke", "#9A8B7A")
          .style("stroke-width", "1px");
    }
</script>

cities.csv

"label","population","country","x","y"
"San Francisco", 750000,"USA",122,-37
"Fresno", 500000,"USA",119,-36
"Lahore",12500000,"Pakistan",74,31
"Karachi",13000000,"Pakistan",67,24
"Rome",2500000,"Italy",12,41
"Naples",1000000,"Italy",14,40
"Rio",12300000,"Brazil",-43,-22
"Sao Paolo",12300000,"Brazil",-46,-23

tweets.json

{
  "tweets": [
    {
      "user": "Al",
      "content": "I really love seafood.",
      "timestamp": " Mon Dec 23 2013 21:30 GMT-0800 (PST)",
      "retweets": [ "Raj", "Pris", "Roy" ],
      "favorites": [ "Sam" ]
    },
    {
      "user": "Al",
      "content": "I take that back, this doesn't taste so good.",
      "timestamp": "Mon Dec 23 2013 21:55 GMT-0800 (PST)",
      "retweets": [ "Roy" ],
      "favorites": []
    },
    {
      "user": "Al",
      "content": "From now on, I'm only eating cheese sandwiches.",
      "timestamp": "Mon Dec 23 2013 22:22 GMT-0800 (PST)",
      "retweets": [],
      "favorites": [ "Roy", "Sam" ]
    },
    {
      "user": "Roy",
      "content": "Great workout!",
      "timestamp": " Mon Dec 23 2013 7:20 GMT-0800 (PST)",
      "retweets": [],
      "favorites": []
    },
    {
      "user": "Roy",
      "content": "Spectacular oatmeal!",
      "timestamp": " Mon Dec 23 2013 7:23 GMT-0800 (PST)",
      "retweets": [],
      "favorites": []
    },
    {
      "user": "Roy",
      "content": "Amazing traffic!",
      "timestamp": " Mon Dec 23 2013 7:47  GMT-0800 (PST)",
      "retweets": [],
      "favorites": []
    },
    {
      "user": "Roy",
      "content": "Just got a ticket for texting and driving!",
      "timestamp": " Mon Dec 23 2013 8:05 GMT-0800 (PST)",
      "retweets": [],
      "favorites": [ "Sam", "Sally", "Pris" ]
    },
    {
      "user": "Pris",
      "content": "Going to have some boiled eggs.",
      "timestamp": " Mon Dec 23 2013 18:23 GMT-0800 (PST)",
      "retweets": [],
      "favorites": [ "Sally" ]
    },
    {
      "user": "Pris",
      "content": "Maybe practice some gymnastics.",
      "timestamp": " Mon Dec 23 2013 19:47  GMT-0800 (PST)",
      "retweets": [],
      "favorites": [ "Sally" ]
    },
    {
      "user": "Sam",
      "content": "@Roy Let's get lunch",
      "timestamp": " Mon Dec 23 2013 11:05 GMT-0800 (PST)",
      "retweets": [ "Pris" ],
      "favorites": [ "Sally", "Pris" ]
    }
  ]
}