Bubble chart label placement algorithm? (preferably in JavaScript)

I imagine you're working with javascript, html and css? Well in any case two approaches come to mind.

First is to formulate it as an optimisation problem. You need to compute the ideal position for each label. This will be based on the size of the bubble, the desired location (i.e. top, down, left, right), and the size of the label (both font and length). Then you need to parameterise your coordinates, for example into a list of 2N elements where N is the number of labels. Then you need to initialise the labels in some position (or a population if using a genetic algorithm) and apply an optimisation algorithm which will require a cost function. This would be based on how far a set of label positions are from the ideal, as well as anything that violates your rules, such as overlapping.

Or, make it a physics problem. 'Attach' each label to its bubble with some rigid link. Give every label and every bubble a repelling force and also add a global and stronger graviational force (in the preferred top/left/right/down direction). Have a short physical simulation until you reach an equilibrium. The maths shouldn't be too hard.


How about this?

An Efficient Algorithm for Scatter Chart Labeling