[英]How do I make circles not over lap on my data visualisation project? p5.js
For my University project I am making a visual representation of data, specifically population. 对于我的大学项目,我将对数据(尤其是总体)进行可视化表示。 So far I have it so the top 50 countries are displayed as circles with the size being relative to the population amount. 到目前为止,我将前50个国家/地区显示为圆形,其大小与人口总数相关。 The position of the circles is completely random and because of this the circles cluster and the data unintelligible. 圆的位置是完全随机的,因此,圆聚集并且数据难以理解。 What code do I have to add in order to make the circles not overlap. 我必须添加什么代码才能使圆不重叠。 Thanks in advance and I apologise if I missed some details I am beginner in coding. 在此先感谢您,如果我错过了一些细节,我很抱歉,我是编码方面的初学者。
the code in its current state. 当前状态的代码。
let population;
//The preload function is executed before initializing the code in setup
//Loads any related data or media files
function preload() {
population = loadJSON("worldpopulation.json");
}
function setup() {
console.log(population); //Return all JSON data
var canvas = createCanvas(1280, 720);
}
function draw(){
noLoop();
console.log(population[2].population / 1000000);
for (let i=0; i<50; i++){
let newSize = population[i].population / 3000000;
let newPosX = random(1280);
let newPosY = random(720);
var r = newSize;
fill(random(255), random(255), random(255));
ellipse(newPosX, newPosY, newSize, newSize);
fill(0);
textAlign(CENTER);
text(population[i].country, newPosX, newPosY-5);
text(population[i].population, newPosX, newPosY+5);
}
The simplest approach might be to keep an array of the rendered circles as you create them. 最简单的方法可能是在创建圆时保留一组渲染的圆。 Then only add valid (non-overlapping) ones to to the rendering layer. 然后,仅将有效的(不重叠)添加到渲染层。
A circle overlaps with another if the distance between their centers is less than the sum of their radii. 如果圆心之间的距离小于其半径之和,则该圆与另一个圆重叠。 In other words, only add Circle2 (with center (x2, y2) and radius r2) if it satisfies the following condition for all pre-existing circles (with centers (x1, y1) and radius r1). 换句话说,如果圆2(具有中心(x2,y2)和半径r2)满足以下条件,则仅添加圆形2(具有中心(x1,y1)和半径r1)。
( (x2-x1)^2 + (y2-y1)^2 ) ^ (1/2) > (r1 + r2) ((x2-x1)^ 2 +(y2-y1)^ 2)^(1/2)>(r1 + r2)
If it doesn't, discard it and try generating another one. 如果不是,则将其丢弃并尝试生成另一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.