简体   繁体   中英

d3 color gradient linear scale not working

I have the following creating two circles for each data point, based on the latitude, longitude. The circles differ in size and color. I'd like for the "fill" in circles1 to be based on a color gradient value returned by colorScale. However, the circles just appear black. What am I getting wrong here?

d3.csv("cities-lived.csv", function(data) {

var colorScale = d3.scale.linear()
    .domain([-15, 7.5, 30])
    .range(["#2c7bb6", "#ffff8c", "#d7191c"])
    .interpolate(d3.interpolateHcl);

var circles1 = svg.selectAll("foo")
    .data(data)
    .enter()
    .append("circle")
    .attr("cx", function(d) {
        return projection([d.lon, d.lat])[0];
    })
    .attr("cy", function(d) {
        return projection([d.lon, d.lat])[1];
    })
    .attr("r", function(d) {
        return Math.sqrt(d.years * 2);
    })
    .style("fill", function(d) {
        return colorScale(d.temp);
    })    
        .style("opacity", 0.85) 

.on("mouseover", function(d) {      
        div.transition()        
           .duration(200)      
           .style("opacity", .9);      
           div.text(d.place)
           .style("left", (d3.event.pageX) + "px")     
           .style("top", (d3.event.pageY - 28) + "px");    
    })   

    // fade out tooltip on mouse out               
    .on("mouseout", function(d) {       
        div.transition()        
           .duration(500)      
           .style("opacity", 0);   
    })

var circles2 = svg.selectAll("foo")
    .data(data)
    .enter()
    .append("circle")
    .attr("cx", function(d) {
        return projection([d.lon, d.lat])[0];
    })
    .attr("cy", function(d) {
        return projection([d.lon, d.lat])[1];
    })
    .attr("r", function(d) {
        return Math.sqrt(d.avg * 2);
    })
        .style("fill", "none")    
        .style("opacity", 0.85) 
        .style("stroke", "black")
        .style("stroke-width", "2");

    // Modification of custom tooltip code provided by Malcolm Maclean, "D3 Tips and Tricks" 
    // http://www.d3noob.org/2013/01/adding-tooltips-to-d3js-graph.html

});  

Having this (shown below) in place of the .style("fill", function(d).... works perfectly fine.

    .style("fill", "rgb(217,91,67)") 

The above code is based on http://blockbuilder.org/anonymous/0e1213b567bcfc74376cc0e9a7238c1b , and the colorscale function is based on http://bl.ocks.org/nbremer/a43dbd5690ccd5ac4c6cc392415140e7 .

Your code is working fine, your issue must be coming from your data :

.style("fill", function(d) {
    return colorScale(d.temp);
})   

d.temp must be undefined

I did a fiddle as an example https://jsfiddle.net/ddspczr1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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