首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >气泡图中y位置的强制碰撞

气泡图中y位置的强制碰撞
EN

Stack Overflow用户
提问于 2019-10-01 06:27:43
回答 1查看 161关注 0票数 1

我正在尝试使用d3.forceSimulation,它将一个力应用于图表圆的y位置,以防止它们重叠。

最终的图表应该是这样的-

我一直在遵循一些例子,但无法让y位置以正确的方式进行调整。不幸的是,我不知道哪里出了问题。任何正确方向的提示都将不胜感激!

到目前为止,这是我的代码:

代码语言:javascript
复制
    //ADDING SKELETON FOR THE CHART//
    let width = 900;
    let height = 300;
    let margin = {x: 50, y:20};

    let chartDiv = d3.select('body').append('div').attr('id', 'bubble-chart');
    let svg = chartDiv.append('svg');
    svg.attr('height', height).attr('width', width + margin.x);

    //SCALES FOR X POSITION//
    let posScale = d3.scaleLinear().domain([(0-overallMax), overallMax]);
    posScale.range([0, width]);

    //SCALES FOR COLOR//
    let colorScale = d3.scaleOrdinal().domain(groupData.map(g=> g[0])).range(d3.schemeSet3);

    //SCALE FOR CIRCLE SIZE//
    let circleScale = d3.scaleLinear().domain([d3.min(data.map(d=> +d.total)), d3.max(data.map(d=> +d.total))])
    .range([3, 10]);

    //SIMULATION PART
    let simulation = d3.forceSimulation().nodes(data)
        .force('center', d=> d3.forceCenter(posScale(d.position), height/2))
        //.force('charge', d3.forceManyBody().strength(.1))
        .force('collision', d3.forceCollide().radius( d => circleScale(+d.total)))
        .on('tick',ticked)

    let circleGroup = svg.append('g').attr('transform', `translate(${margin.x / 2})`);

    let circles = circleGroup.selectAll('circle').data(data).join('circle');
    circles.attr('r', (d)=> circleScale(+d.total))//.attr('cx', (d) => posScale(d.position)).attr('cy', 50);
    .attr("cx", d=> posScale(d.position))
    .attr("cy", height / 2)
    circles.attr('fill', (d)=> colorScale(d.category));
    circles.style('opacity', '0.5');

    // Apply these forces to the nodes and update their positions.
// Once the force algorithm is happy with positions ('alpha' value is low enough), simulations will stop.
    function ticked(){
     circles.attr("cy", d=> d.y).attr('cx', d=> posScale(d.position));

   }

使用上面的代码,我的图表如下所示:

提前谢谢你!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-01 06:53:31

这不是如何创建蜂群图表(这种数据可视化的技术名称)。您应该在模拟中使用forceXforceY来设置位置。在您的案例中:

代码语言:javascript
复制
let simulation = d3.forceSimulation().nodes(data)
    .force("x", d3.forceX(function(d) { 
        return posScale(d.position); 
    }).strength(foo))
    .force("y", d3.forceY(50).strength(bar))
    .force('collision', d3.forceCollide().radius( d => circleScale(d.total)))
    .on('tick',ticked)

然后,根据需要调整强度(foobar),并更改ticked函数以使用模拟提供的xy属性。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58176019

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档