【问题标题】:How to link county and data on hover in D3.js如何在 D3.js 中链接悬停时的县和数据
【发布时间】:2020-11-23 21:47:46
【问题描述】:

我正在尝试获取我加入的数据,以便在悬停/鼠标悬停时显示到正确的县。基于:https://bl.ocks.org/justinlevi/bb5b7c948177179ab65e971aeca4e59b

我已按相应县连接数据,但现在我试图在悬停时显示相应县数据。

目前它只会显示 Object:Object 并在悬停时附加整个数据 json。

[
  {
    "test_date": "2020-11-02T00:00:00.000",
    "county": "Albany",
    "new_positives": "31",
    "cumulative_number_of_positives": "3802",
    "total_number_of_tests": "1432",
    "cumulative_number_of_tests": "188977"
  },
  {
    "test_date": "2020-11-02T00:00:00.000",
    "county": "Allegany",
    "new_positives": "10",
    "cumulative_number_of_positives": "374",
    "total_number_of_tests": "227",
    "cumulative_number_of_tests": "27683"
  },
  {
    "test_date": "2020-11-02T00:00:00.000",
    "county": "Bronx",
    "new_positives": "166",
    "cumulative_number_of_positives": "56165",
    "total_number_of_tests": "7615",
    "cumulative_number_of_tests": "1034425"
  }
 
]

// Width and height
var chart_width     =   800;
var chart_height    =   600;

var color           =   d3.scaleQuantize().range([
    'rgb(255,245,240)', 'rgb(254,224,210)', 'rgb(252,187,161)',
    'rgb(252,146,114)', 'rgb(251,106,74)', 'rgb(239,59,44)',
    'rgb(203,24,29)',   'rgb(165,15,21)', 'rgb(103,0,13)'
]);



// Projection
/*var projection = d3.geoAlbersUsa()
    //.scale([chart_width])
    //.translate([chart_width / 2, chart_height / 2 ]);
var path = d3.geoPath(projection);
*/

//var projection = d3.geoAlbersUsa().fitSize([chart_width, chart_height]);
//var path = d3.geoPath(projection);

/*var projection = d3.geoMercator()

    .scale(4500)
    .translate([chart_width / 2, chart_height / 2])

var path = d3.geoPath(projection);

//var path = d3.geoPath()
   // .projection(projection);
*/

var projection = d3.geoAlbers()
    .center([0,42.954])
    .rotate([75.527,0])
    .parallels([41,44])
    .translate([chart_width/2,chart_height/2])
    .scale(6000);

var path = d3.geoPath()
    .projection(projection)



// Create SVG
var svg             =   d3.select("#chart")
    .append("svg")
    .attr("width", chart_width)
    .attr("height", chart_height);

// Data
d3.json('ny_covid.json').then(function(covid_data){
    color.domain([
        d3.min( covid_data, function(d){
            return d.cumulative_number_of_positives;
        }),
        d3.max( covid_data, function(d){
            return d.cumulative_number_of_positives;
        })
    ]);
    //console.log(covid_data);
    d3.json('nys.json').then(function ( nys_data ){
        nys_data.features.forEach(function(nys_e,nys_i){
            covid_data.forEach(function(z_e, z_i){
                if(nys_e.properties.name !== z_e.county){
                    return null;
                }

                nys_data.features[nys_i].properties.cumulative_number_of_positives = parseFloat(z_e.cumulative_number_of_positives)

            });
        });

        console.log(nys_data.features);

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

        svg.selectAll('path')
            .data( nys_data.features )
            .enter()
            .append('path')
            .attr( 'd', path)
            .attr('fill', function(d){
                var num = d.properties.num;
                return num ? color (num) : '#ddd';
            })
            .attr('stroke', '#fff')
            .attr('stroke-width', 1)
            .on('mouseover', function (d, i) {
                d3.select(this).transition()
                    .duration('50')
                    .attr('opacity', '.85');
                div.transition()
                    .duration(50)
                    .style("opacity", 1);
                let dee = nys_data.features;


                console.log(dee);
                div.html(dee)
                    .style("left", (d3.event.pageX + 10) + "px")
                    .style("top", (d3.event.pageY - 15) + "px");
            })
            .on('mouseout', function (d, i) {
                d3.select(this).transition()
                    .duration('50')
                    .attr('opacity', '1');
                div.transition()
                    .duration('50')
                    .style("opacity", 0);
                //console.log(nys_data.features)
            });
    });
});
#chart{
    width: 1000px;
    height: 800px;
    background-color: #f7f7f7;
    margin: 25px auto;
}


div.tooltip {
    position: absolute;
    width: 60px;
    height: 28px;
    text-align: left;
    padding: .5rem;
    background: #FFFFFF;
    color: #313639;
    border: 1px solid #313639;
    pointer-events: none;
    font-size: 1.3rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>NYS</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="chart"></div>
<script src="https://d3js.org/d3.v5.js"></script>
<script src="app.js"></script>
</body>
</html>

【问题讨论】:

    标签: javascript json d3.js


    【解决方案1】:

    您可以为构成地图的每条路径添加某种识别数据属性。在这种情况下,它可能是:

    .attr('data-county',d=>d.county)
    

    注意:我不记得从要素到县的确切路径。也许。 d.properties.county?

    然后在悬停时,您可以使用 event.target.dataset.county 来匹配数据中的相应对象。然后使用模板文字来填充您的工具提示。

    它可能看起来像这样:

    nysData.features.forEach((el) => {
              if (
                el.properties["county"] === event.target.dataset.county
              ) {
                tooltip.innerHTML = `content you want to pull`;
              }
            });
    

    【讨论】:

      猜你喜欢
      • 2021-11-05
      • 1970-01-01
      • 2017-12-12
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      相关资源
      最近更新 更多