来自csv文件的d3js色标

时间:2018-01-22 11:08:50

标签: javascript csv d3.js

您能告诉我如何使用csv文件中的数据设置色标吗?

var color = d3.scaleLinear()



<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <link rel="stylesheet" type="text/css" href="main.css">
  <title>Zadatak 2</title>

  <style>
        /*.bar {
            fill: dodgerblue;
        }*/
    </style>

</head>
<body>

<svg width="800" height="700"></svg>  

<script>
var svg = d3.select("svg"),
            margin = 200,
            width = svg.attr("width") - margin,
            height = svg.attr("height") - margin


  

    var xScale = d3.scaleBand().range([0, width]).padding(0.4),
            yScale = d3.scaleLinear().range([height, 0]);

    var g = svg.append("g")
            .attr("transform", "translate(" + 100 + "," + 100 + ")");


    
    d3.csv("XYZ.csv", function(error, data) {
        if (error) {
            throw error;
        }
    
    var color = d3.scaleLinear()
        .domain([0, d3.max(data, function(d) { return d.value; })])
        .range(["red", "blue"])

        xScale.domain(data.map(function(d) { return d.fruit; }));
        yScale.domain([0, d3.max(data, function(d) { return d.value; })]);

        g.append("g")
         .attr("transform", "translate(0," + height + ")")
         .call(d3.axisBottom(xScale));

        g.append("g")
         .call(d3.axisLeft(yScale).tickFormat(function(d){
             return d;
         }).ticks(6));


        g.selectAll(".bar")
         .data(data)
         .enter().append("rect")
         .attr("class", "bar")
         .attr("x", function(d) { return xScale(d.fruit); })
         .attr("y", function(d) { return yScale(d.value); })
         .attr("fill",function(d){ return color(d) })
         .attr("width", xScale.bandwidth())
         .attr("height", function(d) { return height - yScale(d.value); });
    });


</script>
  
</body>
</html>
&#13;
&#13;
&#13;

   .domain([0, d3.max(data, function(d) { return d.value; })])
    .range(["red", "blue"])  

 g.selectAll(".bar")
         .data(data)
         .enter().append("rect")
         .attr("class", "bar")
         .attr("x", function(d) { return xScale(d.fruit); })
         .attr("y", function(d) { return yScale(d.value); })
         .attr("fill",function(d){ return color(d) })
         .attr("width", xScale.bandwidth())
         .attr("height", function(d) { return height - yScale(d.value); });
    });

csv文件数据

fruit,value
Apple,2
Orange,4
Kiwi,3
Peach,6
Grape,2

这一个不行。请帮助我。感谢

0 个答案:

没有答案