<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Adarsh Lilha on Medium]]></title>
        <description><![CDATA[Stories by Adarsh Lilha on Medium]]></description>
        <link>https://medium.com/@adarshlilha?source=rss-ab886869fd46------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZWDzzHZUpsfPTZxDmTgBug.jpeg</url>
            <title>Stories by Adarsh Lilha on Medium</title>
            <link>https://medium.com/@adarshlilha?source=rss-ab886869fd46------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 01:15:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adarshlilha/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Removing label overlapping from pretty charts]]></title>
            <link>https://medium.com/@adarshlilha/removing-label-overlapping-from-pretty-charts-8dd2e3581b71?source=rss-ab886869fd46------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dd2e3581b71</guid>
            <category><![CDATA[d3js]]></category>
            <category><![CDATA[annealing]]></category>
            <category><![CDATA[charts]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Adarsh Lilha]]></dc:creator>
            <pubDate>Tue, 06 Mar 2018 15:27:25 GMT</pubDate>
            <atom:updated>2020-08-20T06:25:39.128Z</atom:updated>
            <content:encoded><![CDATA[<p>Very often I used to encounter pretty charts which would make me wonder how can this be built using code? I started off with native SVG, Canvas API but then I came across D3 which exhibits phenomenal concept of joining data with DOM elements. D3 describes itself as —</p><blockquote>“A JavaScript library for producing dynamic, interactive data visualizations in web browsers with HTML,SVG and CSS”</blockquote><p>Since I was already into Javascript, this seemed fantastic. Really? Javascript can do this? I thought. Well JS is everywhere, so hands down it can!</p><p>I picked up the basics of D3 - <a href="https://github.com/d3/d3-scale">scales</a>, <a href="https://github.com/d3/d3-transition">transitions</a>, <a href="https://github.com/d3/d3-selection">selections</a>, <a href="https://github.com/d3/d3-voronoi">voronoi</a> and built few small charts to understand it better.</p><p>But whenever I had gone ahead to draw a chart in browser, one issue inherently made me go crazy was handling labels overlapping. Such a common problem, but no directed solution. I tried to devise algorithm to handle this but either I was not going anywhere or it was never reaching to a solution (approximation problem, as you might have guessed rightly).</p><p>This article is mostly about me taking you on my learning journey. So if you feel I am wrong, or there are better ways to address this, please feel free to comment to the thread.</p><h3>Before we start</h3><p>In this article I start off with building a simple bubble plot from a real dataset and address the label overlapping elephant. You can find the complete code <a href="https://github.com/adarshlilha/movie-gap-rt">here</a>.</p><h3>Lets sit and draw</h3><p>I always wanted to create <a href="https://informationisbeautiful.net/visualizations/star-wars-last-jedi-one-of-the-biggest-rotten-tomatoes-audience-vs-critics-score-splits-ever/">this</a> myself as I can connect with the paradigm so well. So here I will try to replicate the same chart to the best of my ability.</p><p>I grabbed the csv <a href="http://bit.ly/IIB_MovieLove">dataset</a> from the website and started off with the most atomic components of any chart.</p><ul><li>Scales</li><li>Marks</li></ul><p>Here is a glance of the code which creates scale. If you already know this, feel free to jump to the next section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12a62c4cffebc0ec3928e459cc70033e/href">https://medium.com/media/12a62c4cffebc0ec3928e459cc70033e/href</a></iframe><p>After we’re up with scales and axes, we append them to the SVG.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d67c1cc298f8423fa5002b3f8d06ce44/href">https://medium.com/media/d67c1cc298f8423fa5002b3f8d06ce44/href</a></iframe><p>Since we are done with scales, its time to draw the marks.</p><p>We add circles, define the x position (cx), y position (cy), radius (r) and tweak few other encoding channel (fill) and cosmetic (stroke)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a77d2a6b7c9241797f64471c51ec6464/href">https://medium.com/media/a77d2a6b7c9241797f64471c51ec6464/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*O_1if8yktDnl9Lum_z2cjA.gif" /></figure><p>We now see bubbles corresponding to movies positioned by scales.</p><p>Won’t it be great if we are able to understand which circle represents which movie?</p><p>Time to add the labels besides each circle! Let’s start off by adding text elements besides each circle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8640e91b7a96a007cd594852796f464c/href">https://medium.com/media/8640e91b7a96a007cd594852796f464c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*2m9okPRJq9_ux29ZD6qC9w.gif" /></figure><p>This is what I was talking about. The labels are getting overlapped and we end up with a gibberish looking chart. I wish d3 had given a way to fix this. But if you think logically it’s not d3’s job to fix this. Since we are on our own, let’s use an overlap reducing algorithm!</p><h3>Let’s tame the dragon</h3><p>We use the concept of simulated annealing to remove overlaps.</p><blockquote><em>To understand what annealing is and how it works for us here, </em><a href="http://vis.berkeley.edu/courses/cs294-10-fa13/wiki/images/5/55/FP_EvanWang_paper.pdf"><em>go through this paper</em></a><em>.</em></blockquote><p>The idea is something like this. You have to have a quantifiable value which is representative of the label position’s quality. This quality is function of overlapping, distance, orientation etc. We will try to minimise the value to find the best position for our label. There are different method for minimisation. Simulated annealing is one of the many useful one.</p><p>Take your time to read and understand the concept of how annealing works, Not the code yet but the mechanism of energy, weights and cooling and how can they be used together. It’s not simple, but not very difficult also. If you have understood 10% of it then you probably have mastered it.</p><p><a href="https://github.com/adarshlilha/movie-gap-rt/blob/master/label.js">This</a> is an implementation of the same annealing technique we read above. We will now have a deeper look at the algorithm.</p><h4>Understanding the flow</h4><pre>d3.labeler()<br>  .label(labelArray)<br>  .anchor(anchorArray)<br>  .width(width)<br>  .height(height)<br>  .start(2000);</pre><ul><li><em>label</em> takes an array of objects with x, y, name, width, height (labelArray)</li></ul><pre>{ x: 115, y: 580, name: “Walk Hard”, width: 30, height: 8 }</pre><ul><li><em>anchor</em> takes in the array of objects with x, y, radius of circle (anchorArray)</li></ul><pre>{ x: 105, y: 600, r: 7 }</pre><ul><li><em>width</em> and <em>height</em> of the canvas. If a label crosses the boundary, it’s position remains unchanged.</li><li>function <em>start</em> initiates the annealing process. The parameter it gets (2000) is the iteration it does find out the global minima of the annealing process.</li></ul><p><a href="https://github.com/adarshlilha/movie-gap-rt/blob/master/label.js">Label.js</a> is the one which does the magic.</p><h4>Annealing Algorithm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*wPrfBbFPz8ZFkBIkLovoUw.png" /><figcaption>Algorithm for removing overlaps with annealing</figcaption></figure><p>All its saying is, tweak the position of a label keeping every other labels fixed. This tweaking is what we are calling <em>configuration </em>in the algorithm. For the new configuration decide whether the new one is better than the previous one.</p><p>Lets explore the algorithm block by block</p><p><strong>Steps</strong></p><ul><li>First it all starts off by either rotating or moving(translating) labels to a new position.</li><li>Energy is calculated before and after the change using the current position(x, y) and weightage of the overlap.<br><em>Energy</em> is a function which gives the value of the quantitive measure using which we can qualify the quality of the placement.</li><li>If change in energy &lt; 0, keep the new position of the label. It’s better than what we had in the last configuration.</li><li>If change in energy &gt; 0, then for <br>- higher value of T introduce a higher probability of accepting it <br>- lower value of T introduce a lower probability of accepting it<br>The exponential term ensures the dynamic probability assignment to the system and random number is used to have a randomness in acceptance of the probability.</li><li>Decrease the temperature slightly for each iteration. We have initially set it to 1. More the temperature, higher the changes of accepting the new position. Initially annealing accepts all changes and slowly optimises again by lowering temperature.</li></ul><h4><strong>Understanding the code</strong></h4><p>Open the <a href="https://github.com/adarshlilha/movie-gap-rt/blob/master/label.js">label.js</a> file and have a look. A couple of small functions - <em>width</em>, <em>height</em>, <em>label</em> and <em>anchor </em>are self explanatory. They just initialise the global variables with the values passed by the user.</p><p>Next is the <em>start</em> function, this is where everything starts. We assume temperature to be 1.0 and loop a finite amount of times, inside which we iterate the labelArray and then either perform a move or rotate. Also in the end we decrease the temperature by a small amount.</p><p><strong>mcmove function</strong></p><ul><li>Take any random index of the array</li></ul><pre>var i = Math.floor(Math.random() * lab.length);</pre><ul><li>Store it’s (x, y) co-ordinates in two variables</li></ul><pre>var x_old = lab[i].x;<br>var y_old = lab[i].y;</pre><ul><li>Calculate energy</li></ul><pre>var oldEnergy = energy(i);</pre><ul><li>Move label to a new position</li></ul><pre>lab[i].x += (Math.random() — 0.5) * max_move;<br>lab[i].y += (Math.random() — 0.5) * max_move;</pre><ul><li>If new position exceeds the boundary, go back to old position we stored in step 2</li></ul><pre>if (lab[i].x &gt; w) { lab[i].x = x_old; }</pre><ul><li>Calculate energy again</li></ul><pre>var newEnergy = energy(i);</pre><ul><li>Check if</li></ul><pre>Math.random &lt; e^((new energy - old energy) / temperature)</pre><ul><li>If yes, do nothing as we have already moved to new position.<br> - if not, move back to old position using the (x, y) we stored in step 2.</li></ul><p>In the above steps we calculated <em>energy</em> twice. Let’s unravel it now.</p><p><strong>energy function</strong></p><p>Here we increment total energy value for whatever overlapping cases we want to handle and return the total.</p><p>For label-label overlaps</p><ul><li>We store the values of four corners of the rect bounding the label in x21, y21, x22 and y22 variables</li></ul><pre>var x21 = lab[index].x,<br>    y21 = lab[index].y — lab[index].height + 2.0,<br>    x22 = lab[index].x + lab[index].width,<br>    y22 = lab[index].y + 2.0;</pre><ul><li>Iterate over all the labels and calculate the rect corners of all other labels and also find out the area of overlapping.</li></ul><pre>for (var i = 0; i &lt; m; i++) {<br>    if (i != index) {</pre><pre>         //label-label overlap<br>         //positions of 4 corners of rect bounding the text</pre><pre>         x11 = lab[i].x,<br>         y11 = lab[i].y — lab[i].height + 2.0,<br>         x12 = lab[i].x + lab[i].width,<br>         y12 = lab[i].y + 2.0;<br>         x_overlap = Math.max(0, Math.min(x12, x22) — Math.max(x11, x21));<br>         y_overlap = Math.max(0, Math.min(y12, y22) — Math.max(y11, y21));<br>         overlap_area = x_overlap * y_overlap;<br>         ener += (overlap_area * weight_label);<br>}</pre><ul><li>Multiply the overlapped area with weight_label and add it to energy</li></ul><blockquote>Weights represent the intensity of the label overlap in the chart. More the weight, higher the intensity, so that label will go to a new position.</blockquote><pre>var weight_label = 30.0,<br>    weight_label_anc = 30.0,<br>    weight_len = 0.2;</pre><p>We have given more weightage of two labels overlapping and a label overlapping with an anchor(circle), than label overlapping with it’s link line.</p><p>After this<strong>, repeat</strong> the same process for other overlaps, ex - label-anchor(circles)<strong> </strong>overlaps, adding to energy.</p><p>If we have an overlap to be fixed, we are adding a value to overlap which evaluates the condition</p><pre>(Math.random() &lt; Math.exp(-delta_energy / currTemp))</pre><p>to be <strong>true</strong>, accepting the new position of the moved label.</p><p><strong>Cooling Temperature function</strong></p><p>Lastly, we also decrease the temperature by a small amount on each iteration according to the algorithm.</p><h4>Wrapping Up</h4><p>Finally, we move back to our html file</p><ul><li>create an array with<em> x, y, radiu</em>s values of circles(AnchorArray) and</li><li>create second array with <em>x, y, name, width, height</em>, values of labels(labelArray)</li></ul><p>and pass them to our annealing code (<a href="https://github.com/adarshlilha/movie-gap-rt/blob/master/label.js">label.js</a>). This is pretty straightforward so have a look.</p><p>As a touchup, we add some <a href="https://github.com/adarshlilha/movie-gap-rt/blob/master/style.css">styling</a> to our chart, lines connecting labels to the circle it represents and also render the labels and lines with new position with some transition</p><pre>labels<br>    .transition()<br>    .duration(1500)<br>    .attr(“x”, (d) =&gt; d.x)<br>    .attr(“y”, (d) =&gt; d.y);</pre><p>Once done, this is what we get!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m4fCm1iyYxo-5O3E2cce4A.gif" /><figcaption>Removing overlaps with transition</figcaption></figure><p><strong>nsweeps why?</strong></p><p>At this point one question pops up in my head-</p><blockquote>“Why do we pass 1000 to start function and iterate 1000 times only. This is not what the algorithm says.”</blockquote><p>Yes, at first this may seem weird but it is required because if the dataset grows big, it may not be possible to remove overlaps. At that point the program may get stuck in an infinite loop. This is done to get the optimum output and prevent that from happening simultaneously.</p><p><strong>References and Resources</strong></p><ul><li>D3-Labeler <a href="http://vis.berkeley.edu/courses/cs294-10-fa13/wiki/images/5/55/FP_EvanWang_paper.pdf">Paper</a> by Evan Wang</li><li><a href="https://github.com/tinker10/D3-Labeler">D3-Labeler</a> code for reference</li><li><a href="http://gifbrewery.com/">GIF Brewery</a> to create the gifs</li></ul><p><strong>Contribute</strong></p><p>Would like to improve the technique or code? Feel free to reach out.</p><p><a href="https://github.com/adarshlilha/movie-gap-rt">adarshlilha/movie-gap-rt</a></p><p>Thanks for reading, If you liked the article, click the 💚 below so other people will see it on Medium.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dd2e3581b71" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>