问题描述
我试图使用 d3.layout.force
创建一个强制有向图,我需要容器可以调整大小 - 这是我想要可以根据大小计算适当的费用和链接距离值,或者d3用一些神奇的方式为我做这件事。
I'm trying to make a force directed graph using d3.layout.force
, and I need the container to be resizable - that is I'd like to be able calculate appropriate charge and linkDistance values based on the size, or have d3 do it for me in some magical way.
我做了一个尝试(链接:),它只使用节点。我将电荷设置为一个值,该值基于圆形半径周围的节点数量,形状类似。
I've made an attempt (link: http://jsfiddle.net/VHdUe/6/) which only uses nodes. I'm setting the charge to a value that's based on the number of nodes that would fit across the radius of the circle that it tends to be shaped like.
解决方案适用于一些中型容器,但如果你点击调整几次,你可以看到它并不适用于所有尺寸...
The solution works for some middle-sized containers, but if you click resize a few times, you can see it doesn't really work for all sizes...
前进我可以看到是使用svg缩放变换,这将弄乱我的元素的大小不利。任何其他选项?
The only way forward I can see is using an svg scale transform, which will mess up the size of my elements unfavorable. Any other options?
PS:我看到(),但我宁愿有一个基于重力的解决方案比边界框一个。
PS: I have seen http://mbostock.github.com/d3/talk/20110921/bounding.html (the answer to D3 force directed layout with bounding box), but I'd rather have a gravity-based solution than a bounding box one.
推荐答案
除了和,您还有。如果你想让图形相对于布局尺寸保持相同的相对密度,那么你需要同时扩展电荷和重力。这些是确定blob的整体大小的主要两个计算力。有关详情,请参见。
In addition to charge and linkDistance, you also have gravity. If you want the graph to maintain the same relative density to the layout size, then you'll want to scale both charge and gravity. These are the main two computing forces that determine the overall size of the blob. See my force layout talk for more details.
我尝试了几个不同的版本,这个似乎工作得很好:
I tried a few different versions, and this one seemed to work pretty well:
var k = Math.sqrt(nodes.length / (width * height));
layout
.charge(-10 / k)
.gravity(100 * k)
这里 nodes.length /(width * height)
与图形密度成线性比例:节点的面积除以区域的布局。收费力遵循,因此可能解释为什么平方根好。 D3的重力是一个虚拟弹簧,随着距离布局中心的距离线性变化,因此随着图形变得更加密集,这也增加了重力,并阻止了节点逃离边界框。
Here nodes.length / (width * height)
is linearly proportional to the graph density: the area of the nodes divided by the area of the layout. The charge force follows the inverse-square law, so that might explain why the square root works well. D3's "gravity" is a virtual spring that scales linearly with distance from the layout center, so this also increases the gravity as the graph becomes denser and discourages nodes from escaping the bounding box.
这篇关于基于尺寸的充电 - d3力布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!