基于大小的充电 - d3 力布局 [英] Charge based on size - d3 force layout

查看:18
本文介绍了基于大小的充电 - d3 力布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 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.

我已经尝试过(链接:http://jsfiddle.net/VHdUe/6/) 只使用节点.我将电荷设置为一个值,该值基于适合圆形半径的节点数,该圆的半径通常为圆形.

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:我看过http://mbostock.github.com/d3/talk/20110921/bounding.html(D3的答案带有边界框的强制定向布局),但我宁愿使用基于重力的解决方案而不是边界框解决方案.

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.

推荐答案

除了 收费linkDistance,你也有 重力.如果您希望图形与布局大小保持相同的相对密度,那么您需要同时缩放电荷和重力.这是决定 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 力布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆