D3多线图表,颜色相同

时间:2015-04-19 13:38:36

标签: javascript d3.js

我是D3的新手,我的要求是获得多个折线图并为每个数据点提供点。我从这个例子开始:http://www.d3noob.org/2014/07/d3js-multi-line-graph-with-automatic.html我在线上添加了点,但是我无法让点变成相同的颜色。

以下是我迄今为止没有运气的其他例子。 Adding point and value to line chart... how to color the point like the line? Create points on a D3 multiline graph

这是我的代码的副本。任何帮助将不胜感激。谢谢。

<!DOCTYPE html>
<style> /* use CSS style to set properties for each axis line */

.axis path,
.axis line {
    fill: none;
    stroke: black;
    stroke-width: 2;
    shape-rendering: crispEdges;
}

div.tooltip {   
  position: absolute;           
  text-align: center;           
  width: 60px;                  
  height: 28px;                 
  padding: 2px;             
  font: 12px sans-serif;        
  background: lightsteelblue;   
  border: 0px;      
  border-radius: 8px;           
  pointer-events: none;         
}

</style>
<body>

<!-- load the d3.js library --> 
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js">      </script>

<script>

// Set the canvas dimensions
var margin = {top: 30, right: 20, bottom: 70, left: 50},
    width = 950 - margin.left - margin.right,
    height = 450 - margin.top - margin.bottom;

// Set the x and y values
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

//Format d.date variable
var formatTime = d3.time.format("%Y");

// Define the axes
var xAxis = d3.svg.axis().scale(x)
    .orient("bottom").ticks(15);

var yAxis = d3.svg.axis().scale(y)
    .orient("left").ticks(10);

// Define the line
var dataline = d3.svg.line()    
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.data); });

// Adds the canvas
var svg = d3.select("body")
    .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .attr("font", "Arial")
        .style("font-size","14px")
    .append("g")
        .attr("transform", 
              "translate(" + margin.left + "," + margin.top + ")");

// Add a title
var title = svg.append("text")
    .attr("x", (width / 2))             
    .attr("y", 0 - (margin.top / 2))
    .attr("text-anchor", "middle")  
    .style("font-size", "16px") 
    .style("text-decoration", "underline")  
    .text("Climate Change");

// Add the div for the tooltip
var div = d3.select("body").append("div")   
    .attr("class", "tooltip")               
    .style("opacity", 0);

// Get the data
d3.csv("Climate_data.csv", function(error, data) {
    data.forEach(function(d) {
        d.date = new Date(+d.date,0,1);
        d.data = +d.data;
    });

  // Nest the entries by symbol
  var dNest = d3.nest()
    .key(function(d) {return d.symbol;})
    .entries(data);

  // set the colour scale
  var color = d3.scale.category10();

  // Scale the range of the data
  x.domain(d3.extent(data, function(d) { return d.date; }));
  y.domain([0, d3.max(data, function(d) { return d.data; })]);

  // spacing for the legend
  legendSpace = width/dNest.length;

  // Add the X Axis
  svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

  // Add the Y Axis
  svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

  // Loop through each symbol / key
  dNest.forEach(function(d,i) {

    var lines = svg.append("path")
                    .attr("class", "line")
                    .style("stroke", function() { // Add the colours dynamically
                        return d.color = color(d.key); })
                    .attr("id", 'tag'+d.key.replace(/\s+/g, '')) // assign ID
                    .attr("stroke-width", 2)
                    .attr("fill","none")
                    .attr("d", dataline(d.values));

    // Add the dots for the tooltip
    svg.selectAll("dot")
        .data(data)
    .enter().append("circle")  
        .attr("r", 2)           
        .attr("cx", function(d) { return x(d.date); })       
        .attr("cy", function(d) { return y(d.data); })
        .style("fill", lines.each(function(i) { 
             return d.color = color(i); }))
        .attr("id", 'tag'+d.key.replace(/\s+/g, '')) // assign ID
        .on("mouseover", function(d) {      
            div.transition()        
                .duration(200)      
                .style("opacity", .9);      
            div .html("Year: " + formatTime(d.date) + "<br/>"  + d.data)  
                .style("left", (d3.event.pageX) + "px")     
                .style("top", (d3.event.pageY - 28) + "px");    
            })                  
        .on("mouseout", function(d) {       
            div.transition()        
                .duration(500)      
                .style("opacity", 0); 
        });

    // Add the Legend
    svg.append("text")
        .attr("x", (legendSpace/2)+i*legendSpace)  // space legend
        .attr("y", height + (margin.bottom/2)+ 5)
        .attr("class", "legend")    // style the legend
        .style("font-size","15px")  // Change the font size
        .style("font-weight", "bold") // Change the font to bold
        .style("text-anchor", "middle") // center the legend
        .style("fill", function() { // Add the colours dynamically
            return d.color = color(d.key); })
        .on("click", function(){
            // Determine if current line is visible 
            var active   = d.active ? false : true,
            newOpacity = active ? 0 : 1; 
            // Hide or show the elements based on the ID
            d3.select("#tag"+d.key.replace(/\s+/g, ''))
                .transition().duration(100) 
                .style("opacity", newOpacity); 
            // Update whether or not the elements are active
            d.active = active;
            })  
        .text(d.key); 

});

});

</script>
</body>

以下是我的数据:Climate_data.csv

symbol  date    data
Winter  1976    3.9
Winter  1977    1.3  
Winter  1978    2
Winter  1979    3.2
Winter  1980    3.5
Winter  1981    2.3
Winter  1982    2.3
Winter  1983    4.7
Winter  1984    4.3
Winter  1985    4.7
Winter  1986    4.1
Winter  1987    4.4
Winter  1988    3.3
Winter  1989    3.8
Winter  1990    4.3
Winter  1991    5.4
Winter  1992    4.5
Winter  1993    3.8
Winter  1994    2.6
Winter  1995    5.3
Winter  1996    2.9
Winter  1997    3.7
Winter  1998    4.7
Winter  1999    5
Winter  2000    4.2
Winter  2001    4.3
Winter  2002    5.7
Winter  2003    2.4
Winter  2004    3.2
Winter  2005    3.2
Winter  2006    5.7
Winter  2007    5
Winter  2008    5.4
Winter  2009    4.1
Winter  2010    3.83
Winter  2011    3.02
Spring  1976    11.1
Spring  1977    10.7
Spring  1978    9.4
Spring  1979    10.7
Spring  1980    10.5
Spring  1981    10.7
Spring  1982    9.9
Spring  1983    10.9
Spring  1984    11
Spring  1985    11
Spring  1986    11.5
Spring  1987    11.6
Spring  1988    10.8
Spring  1989    10.7
Spring  1990    10.8
Spring  1991    12.3
Spring  1992    11
Spring  1993    11
Spring  1994    10.6
Spring  1995    11.4
Spring  1996    9.7
Spring  1997    9.8
Spring  1998    11.5
Spring  1999    12.5
Spring  2000    11.8
Spring  2001    11.5
Spring  2002    12
Spring  2003    10.5
Spring  2004    11.5
Spring  2005    11
Spring  2006    12.1
Spring  2007    11.3
Spring  2008    11.9
Spring  2009    11.4
Spring  2010    13.04
Spring  2011    11.3
Summer  1976    18.9
Summer  1977    19.6
Summer  1978    18.9
Summer  1979    19.9
Summer  1980    19.6
Summer  1981    20.1
Summer  1982    19.7
Summer  1983    19.6
Summer  1984    19.7
Summer  1985    20.2
Summer  1986    19.4
Summer  1987    19.7
Summer  1988    19.2
Summer  1989    19.7
Summer  1990    19.9
Summer  1991    20
Summer  1992    19.1
Summer  1993    19.9
Summer  1994    20.1
Summer  1995    20.3
Summer  1996    18.7
Summer  1997    18.8
Summer  1998    20
Summer  1999    20.9
Summer  2000    20.4
Summer  2001    20.6
Summer  2002    20.8
Summer  2003    20.3
Summer  2004    20
Summer  2005    20.3
Summer  2006    20.5
Summer  2007    20.2
Summer  2008    20.7
Summer  2009    19.9
Summer  2010    20.82
Summer  2011    20.43
Fall    1976    9.7
Fall    1977    11.5
Fall    1978    12.1
Fall    1979    12.3
Fall    1980    10.7
Fall    1981    10.7
Fall    1982    12.5
Fall    1983    12.6
Fall    1984    12.8
Fall    1985    12.8
Fall    1986    12.4
Fall    1987    11.3
Fall    1988    11.2
Fall    1989    11
Fall    1990    13.1
Fall    1991    12.4
Fall    1992    11.2
Fall    1993    11.9
Fall    1994    12.9
Fall    1995    12.9
Fall    1996    10.9
Fall    1997    11
Fall    1998    12.2
Fall    1999    13.1
Fall    2000    12.4
Fall    2001    13.5
Fall    2002    12
Fall    2003    12.4
Fall    2004    12.1
Fall    2005    12.5
Fall    2006    13.8
Fall    2007    13.2
Fall    2008    12.5
Fall    2009    12
Fall    2010    11.56
Fall    2011    13.45
Cold water  1984    7.1
Cold water  1985    6.4
Cold water  1986    6.3
Cold water  1987    6.7
Cold water  1988    6.8
Cold water  1989    7.6
Cold water  1990    7.7
Cold water  1991    7.3
Cold water  1992    6.9
Cold water  1993    6.9
Cold water  1994    6.1
Cold water  1995    6.4
Cold water  1996    6.3
Cold water  1997    6.7
Cold water  1998    6.8
Cold water  1999    6.9
Cold water  2000    6.4
Cold water  2001    6.2
Cold water  2002    6.3
Cold water  2003    5.6
Cold water  2004    5.9
Cold water  2005    4.9
Cold water  2006    4.7
Cold water  2007    6
Cold water  2008    6
Cold water  2009    5.6
Cold water  2010    6.1
Cold water  2011    5.9
Cold water  2012    5.9
Warm water  1984    6.1
Warm water  1985    5
Warm water  1986    4.7
Warm water  1987    3.6
Warm water  1988    4
Warm water  1989    4.1
Warm water  1990    4.2
Warm water  1991    4.7
Warm water  1992    4.7
Warm water  1993    3.8
Warm water  1994    4.6
Warm water  1995    4.1
Warm water  1996    4.8
Warm water  1997    5.2
Warm water  1998    5.2
Warm water  1999    5.8
Warm water  2000    6.2
Warm water  2001    5.3
Warm water  2002    7.5
Warm water  2003    5.7
Warm water  2004    5.2
Warm water  2005    4.6
Warm water  2006    5.8
Warm water  2007    5.9
Warm water  2008    6
Warm water  2009    5.3
Warm water  2010    6
Warm water  2011    6.5
Warm water  2012    8

1 个答案:

答案 0 :(得分:1)

在设置fill的{​​{1}}时,代码中的错误就在此行:

circle

这会返回.style("fill", lines.each(function(i) { return d.color = color(i); })) ,因为undefined函数不会返回值。由于Array.each不是有效颜色,因此您的undefined内填充了默认的黑色。

您需要设置与之前circle相同的颜色,即(来自您的代码):

paths

在此,您使用.style("stroke", function() { // Add the colours dynamically return d.color = color(d.key); }) category10 ordinal scale根据数据color分配path的{​​{1}}颜色价值,例如冬天冷水。现在,如果你给它们相同的输入,序数标度会返回相同的输出。因此,在stroke key代码中,您需要提供相同的值。由于您在那里使用circle变量(而不是fill定义中的data),您需要访问其dNest属性,因为这样做了其中像 Winter 这样的值。因此,正确替换path代码如下:

symbol

您可以查看整个code working on JSFiddle。除了fill行之外,我只更改了CSV加载逻辑,我删除了AJAX .style("fill", function(d) { return color(d.symbol) }) ,将值内联到style变量并使用d3.csv()进行解析。它提供与climate_data相同的输出,只是没有AJAX调用。

顺便说一句,你的方法并不完全是 D3方式。在创建d3.csv.parse()时,您应该使用选择(使用d3.csv().data())而不是.enter()。查看JSFiddle code