javascript 将d3.hexbin可视化适配到svg元素中

q43xntqr  于 2023-02-15  发布在  Java
关注(0)|答案(1)|浏览(115)

我正在尝试将d3.js hexbin可视化效果放入选定的svg元素中。然而,至少外部的六边形被元素边框切成了两半。我尝试在hexbin缩放中应用较小的宽度和高度,但似乎没有任何效果。可能是视图框有问题?
有人能帮我吗?先谢了。

var rect = document.querySelector('#dash'),
    width = rect.offsetWidth,
    height = rect.offsetHeight;

// set the dimensions and margins of the graph
var margin = {top: 50, right: 30, bottom: 30, left: 60}

var svg = d3.select("div#dash")
.append("svg")
 .attr("preserveAspectRatio", "xMinYMin meet")
 .attr("viewBox", "0 0 " + String(2000) + " " +  String(2000) )
 .classed("svg-content", true)
 .append("g")
 
var randomX = d3.randomNormal(width, 80)
var randomY = d3.randomNormal(height, 80)

points = d3.range(200).map(function() { return [randomX(), randomY()]; });

var color = d3.scaleSequential(d3.interpolateLab("white", "blue")).domain([0, 20]);

var graph_width = width - width/10
var graph_height = height - height/10

var hexbin = d3.hexbin()
    .size([graph_width, graph_height])
    .radius(20);

svg.append("g")
  .selectAll(".hexagon")
    .data(hexbin(points))
  .enter().append("path")
    .attr("class", "hexagon")
    .attr("d", hexbin.hexagon())
    .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
    .style("fill", function(d) { return color(d.length); });
<html>
<head>
</head>

<body>

<div id="dash" class="svg-container"></div>    
    
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-hexbin.v0.2.min.js"></script>
</body>
</html>
wlzqhblo

wlzqhblo1#

1.显式设置svg的widthheight
1.删除viewBox
1.使用简单随机化

const rect = document.querySelector('#dash');
const width = rect.offsetWidth;
const height = rect.offsetHeight;
const radius = 20;

const svg = d3.select("div#dash")
.append("svg")
.attr("width", width)
.attr("height", height)
 .classed("svg-content", true)
 .append("g")
 
points = d3.range(200)
  .map(function() { return [Math.random() * width, Math.random() * height]; })
  .filter(point => point[0] > radius && point[0] < width - radius * 2 && point[1] > radius && point[1] < height - radius);

const color = d3.scaleSequential(d3.interpolateLab("white", "blue")).domain([0, 20]);

var hexbin = d3.hexbin()
.size([width, height])
.radius(radius);

svg.append("g")
  .selectAll(".hexagon")
.data(hexbin(points))
  .enter().append("path")
.attr("class", "hexagon")
.attr("d", hexbin.hexagon())
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.style("fill", function(d) { return color(d.length); });
#dash {
  width: 300px;
  height: 200px;
  padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<script src="https://d3js.org/d3-hexbin.v0.2.min.js"></script>

<div id="dash" class="svg-container"></div>

相关问题