Skip to content

Instantly share code, notes, and snippets.

@bumbeishvili
Last active January 19, 2018 15:41
Show Gist options
  • Save bumbeishvili/9ca6cdcfdd50b36af09c0b9d729a4adb to your computer and use it in GitHub Desktop.
Save bumbeishvili/9ca6cdcfdd50b36af09c0b9d729a4adb to your computer and use it in GitHub Desktop.
most used Georgian words
license: mit
// Word cloud layout by Jason Davies, http://www.jasondavies.com/word-cloud/
// Algorithm due to Jonathan Feinberg, http://static.mrfeinberg.com/bv_ch03.pdf
(function (exports) {
function cloud() {
var size = [256, 256],
text = cloudText,
font = cloudFont,
fontSize = cloudFontSize,
fontStyle = cloudFontNormal,
fontWeight = cloudFontNormal,
rotate = cloudRotate,
padding = cloudPadding,
spiral = archimedeanSpiral,
words = [],
timeInterval = Infinity,
event = d3.dispatch("word", "end"),
timer = null,
cloud = {};
cloud.start = function () {
var board = zeroArray((size[0] >> 5) * size[1]),
bounds = null,
n = words.length,
i = -1,
tags = [],
data = words.map(function (d, i) {
d.text = text.call(this, d, i);
d.font = font.call(this, d, i);
d.style = fontStyle.call(this, d, i);
d.weight = fontWeight.call(this, d, i);
d.rotate = rotate.call(this, d, i);
d.size = ~~fontSize.call(this, d, i);
d.padding = padding.call(this, d, i);
return d;
}).sort(function (a, b) { return b.size - a.size; });
if (timer) clearInterval(timer);
timer = setInterval(step, 0);
step();
return cloud;
function step() {
var start = +new Date,
d;
while (+new Date - start < timeInterval && ++i < n && timer) {
d = data[i];
d.x = (size[0] * (Math.random() + .5)) >> 1;
d.y = (size[1] * (Math.random() + .5)) >> 1;
cloudSprite(d, data, i);
if (d.hasText && place(board, d, bounds)) {
tags.push(d);
// event.word(d);
if (bounds) cloudBounds(bounds, d);
else bounds = [{ x: d.x + d.x0, y: d.y + d.y0 }, { x: d.x + d.x1, y: d.y + d.y1 }];
// Temporary hack
d.x -= size[0] >> 1;
d.y -= size[1] >> 1;
}
}
if (i >= n) {
cloud.stop();
if (d3.version.startsWith('4.')) {
event.call('end',tags, bounds);
} else if (d3.version.startsWith('3.')) {
event.end(tags, bounds);
};
}
}
}
cloud.stop = function () {
if (timer) {
clearInterval(timer);
timer = null;
}
return cloud;
};
cloud.timeInterval = function (x) {
if (!arguments.length) return timeInterval;
timeInterval = x == null ? Infinity : x;
return cloud;
};
function place(board, tag, bounds) {
var perimeter = [{ x: 0, y: 0 }, { x: size[0], y: size[1] }],
startX = tag.x,
startY = tag.y,
maxDelta = Math.sqrt(size[0] * size[0] + size[1] * size[1]),
s = spiral(size),
dt = Math.random() < .5 ? 1 : -1,
t = -dt,
dxdy,
dx,
dy;
while (dxdy = s(t += dt)) {
dx = ~~dxdy[0];
dy = ~~dxdy[1];
if (Math.min(dx, dy) > maxDelta) break;
tag.x = startX + dx;
tag.y = startY + dy;
if (tag.x + tag.x0 < 0 || tag.y + tag.y0 < 0 ||
tag.x + tag.x1 > size[0] || tag.y + tag.y1 > size[1]) continue;
// TODO only check for collisions within current bounds.
if (!bounds || !cloudCollide(tag, board, size[0])) {
if (!bounds || collideRects(tag, bounds)) {
var sprite = tag.sprite,
w = tag.width >> 5,
sw = size[0] >> 5,
lx = tag.x - (w << 4),
sx = lx & 0x7f,
msx = 32 - sx,
h = tag.y1 - tag.y0,
x = (tag.y + tag.y0) * sw + (lx >> 5),
last;
for (var j = 0; j < h; j++) {
last = 0;
for (var i = 0; i <= w; i++) {
board[x + i] |= (last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0);
}
x += sw;
}
delete tag.sprite;
return true;
}
}
}
return false;
}
cloud.words = function (x) {
if (!arguments.length) return words;
words = x;
return cloud;
};
cloud.size = function (x) {
if (!arguments.length) return size;
size = [+x[0], +x[1]];
return cloud;
};
cloud.font = function (x) {
if (!arguments.length) return font;
font = d3.functor(x);
return cloud;
};
cloud.fontStyle = function (x) {
if (!arguments.length) return fontStyle;
fontStyle = d3.functor(x);
return cloud;
};
cloud.fontWeight = function (x) {
if (!arguments.length) return fontWeight;
fontWeight = d3.functor(x);
return cloud;
};
cloud.rotate = function (x) {
if (!arguments.length) return rotate;
rotate = d3.functor(x);
return cloud;
};
cloud.text = function (x) {
if (!arguments.length) return text;
text = d3.functor(x);
return cloud;
};
cloud.spiral = function (x) {
if (!arguments.length) return spiral;
spiral = spirals[x + ""] || x;
return cloud;
};
cloud.fontSize = function (x) {
if (!arguments.length) return fontSize;
fontSize = d3.functor(x);
return cloud;
};
cloud.padding = function (x) {
if (!arguments.length) return padding;
padding = d3.functor(x);
return cloud;
};
return d3.rebind(cloud, event, "on");
}
function cloudText(d) {
return d.text;
}
function cloudFont() {
return "serif";
}
function cloudFontNormal() {
return "normal";
}
function cloudFontSize(d) {
return Math.sqrt(d.value);
}
function cloudRotate() {
return (~~(Math.random() * 6) - 3) * 30;
}
function cloudPadding() {
return 1;
}
// Fetches a monochrome sprite bitmap for the specified text.
// Load in batches for speed.
function cloudSprite(d, data, di) {
if (d.sprite) return;
c.clearRect(0, 0, (cw << 5) / ratio, ch / ratio);
var x = 0,
y = 0,
maxh = 0,
n = data.length;
--di;
while (++di < n) {
d = data[di];
c.save();
c.font = d.style + " " + d.weight + " " + ~~((d.size + 1) / ratio) + "px " + d.font;
var w = c.measureText(d.text + "m").width * ratio,
h = d.size << 1;
if (d.rotate) {
var sr = Math.sin(d.rotate * cloudRadians),
cr = Math.cos(d.rotate * cloudRadians),
wcr = w * cr,
wsr = w * sr,
hcr = h * cr,
hsr = h * sr;
w = (Math.max(Math.abs(wcr + hsr), Math.abs(wcr - hsr)) + 0x1f) >> 5 << 5;
h = ~~Math.max(Math.abs(wsr + hcr), Math.abs(wsr - hcr));
} else {
w = (w + 0x1f) >> 5 << 5;
}
if (h > maxh) maxh = h;
if (x + w >= (cw << 5)) {
x = 0;
y += maxh;
maxh = 0;
}
if (y + h >= ch) break;
c.translate((x + (w >> 1)) / ratio, (y + (h >> 1)) / ratio);
if (d.rotate) c.rotate(d.rotate * cloudRadians);
c.fillText(d.text, 0, 0);
if (d.padding) c.lineWidth = 2 * d.padding, c.strokeText(d.text, 0, 0);
c.restore();
d.width = w;
d.height = h;
d.xoff = x;
d.yoff = y;
d.x1 = w >> 1;
d.y1 = h >> 1;
d.x0 = -d.x1;
d.y0 = -d.y1;
d.hasText = true;
x += w;
}
var pixels = c.getImageData(0, 0, (cw << 5) / ratio, ch / ratio).data,
sprite = [];
while (--di >= 0) {
d = data[di];
if (!d.hasText) continue;
var w = d.width,
w32 = w >> 5,
h = d.y1 - d.y0;
// Zero the buffer
for (var i = 0; i < h * w32; i++) sprite[i] = 0;
x = d.xoff;
if (x == null) return;
y = d.yoff;
var seen = 0,
seenRow = -1;
for (var j = 0; j < h; j++) {
for (var i = 0; i < w; i++) {
var k = w32 * j + (i >> 5),
m = pixels[((y + j) * (cw << 5) + (x + i)) << 2] ? 1 << (31 - (i % 32)) : 0;
sprite[k] |= m;
seen |= m;
}
if (seen) seenRow = j;
else {
d.y0++;
h--;
j--;
y++;
}
}
d.y1 = d.y0 + seenRow;
d.sprite = sprite.slice(0, (d.y1 - d.y0) * w32);
}
}
// Use mask-based collision detection.
function cloudCollide(tag, board, sw) {
sw >>= 5;
var sprite = tag.sprite,
w = tag.width >> 5,
lx = tag.x - (w << 4),
sx = lx & 0x7f,
msx = 32 - sx,
h = tag.y1 - tag.y0,
x = (tag.y + tag.y0) * sw + (lx >> 5),
last;
for (var j = 0; j < h; j++) {
last = 0;
for (var i = 0; i <= w; i++) {
if (((last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0))
& board[x + i]) return true;
}
x += sw;
}
return false;
}
function cloudBounds(bounds, d) {
var b0 = bounds[0],
b1 = bounds[1];
if (d.x + d.x0 < b0.x) b0.x = d.x + d.x0;
if (d.y + d.y0 < b0.y) b0.y = d.y + d.y0;
if (d.x + d.x1 > b1.x) b1.x = d.x + d.x1;
if (d.y + d.y1 > b1.y) b1.y = d.y + d.y1;
}
function collideRects(a, b) {
return a.x + a.x1 > b[0].x && a.x + a.x0 < b[1].x && a.y + a.y1 > b[0].y && a.y + a.y0 < b[1].y;
}
function archimedeanSpiral(size) {
var e = size[0] / size[1];
return function (t) {
return [e * (t *= .1) * Math.cos(t), t * Math.sin(t)];
};
}
function rectangularSpiral(size) {
var dy = 4,
dx = dy * size[0] / size[1],
x = 0,
y = 0;
return function (t) {
var sign = t < 0 ? -1 : 1;
// See triangular numbers: T_n = n * (n + 1) / 2.
switch ((Math.sqrt(1 + 4 * sign * t) - sign) & 3) {
case 0: x += dx; break;
case 1: y += dy; break;
case 2: x -= dx; break;
default: y -= dy; break;
}
return [x, y];
};
}
// TODO reuse arrays?
function zeroArray(n) {
var a = [],
i = -1;
while (++i < n) a[i] = 0;
return a;
}
var cloudRadians = Math.PI / 180,
cw = 1 << 11 >> 5,
ch = 1 << 11,
canvas,
ratio = 1;
if (typeof document !== "undefined") {
canvas = document.createElement("canvas");
canvas.width = 1;
canvas.height = 1;
ratio = Math.sqrt(canvas.getContext("2d").getImageData(0, 0, 1, 1).data.length >> 2);
canvas.width = (cw << 5) / ratio;
canvas.height = ch / ratio;
} else {
// node-canvas support
var Canvas = require("canvas");
canvas = new Canvas(cw << 5, ch);
}
var c = canvas.getContext("2d"),
spirals = {
archimedean: archimedeanSpiral,
rectangular: rectangularSpiral
};
c.fillStyle = c.strokeStyle = "red";
c.textAlign = "center";
exports.cloud = cloud;
})(typeof exports === "undefined" ? d3.layout || (d3.layout = {}) : exports);
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="d3.layout.cloud.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<div class="container centered">
<div id="myGraph"></div>
</div>
<script>
d3.json("testdata.json", data => {
var chart = renderChart()
.svgHeight(800)
.container('#myGraph')
.data({ values: data })
.responsive(true)
.run()
})
/*
This code is based on following convention:
https://github.com/bumbeishvili/d3-coding-conventions
*/
function renderChart(params) {
// exposed variables
var attrs = {
id: 'id' + Math.floor((Math.random() * 1000000)),
svgWidth: 400,
svgHeight: 400,
marginTop: 5,
marginBottom: 5,
marginRight: 5,
marginLeft: 5,
container: 'body',
responsive: false,
data: null
};
/*############### IF EXISTS OVERWRITE ATTRIBUTES FROM PASSED PARAM ####### */
var attrKeys = Object.keys(attrs);
attrKeys.forEach(function (key) {
if (params && params[key]) {
attrs[key] = params[key];
}
})
//innerFunctions which will update visuals
var updateData;
//main chart object
var main = function (selection) {
selection.each(function scope() {
//get container
var container = d3.select(this);
if (attrs.responsive) {
setDimensions();
}
//calculated properties
var calc = {}
calc.chartLeftMargin = attrs.marginLeft;
calc.chartTopMargin = attrs.marginTop;
calc.chartWidth = attrs.svgWidth - attrs.marginRight - calc.chartLeftMargin;
calc.chartHeight = attrs.svgHeight - attrs.marginBottom - calc.chartTopMargin;
calc.centerX = calc.chartWidth / 2;
calc.centerY = calc.chartHeight / 2;
calc.minMax = d3.extent(attrs.data.values, d => d.value);
//drawing containers
//##################### SCALES ###################
var scales = {};
scales.fontSize = d3.scaleSqrt()
.range([10, 100])
.domain(calc.minMax);
scales.color = d3.scaleOrdinal(d3.schemeCategory20b);
//###################### LAYOUTS #################
var layouts = {};
layouts.cloud = d3.layout.cloud()
.timeInterval(Infinity)
.size([calc.chartWidth, calc.chartHeight])
.fontSize(function (d) {
return scales.fontSize(+d.value);
})
.text(function (d) {
return d.key;
})
.font('impact')
.spiral('archimedean')
.stop()
.words(attrs.data.values)
.on("end", function (bounds) {
var index = bounds ? Math.min(
calc.chartWidth / Math.abs(bounds[1].x - calc.centerX),
calc.chartWidth / Math.abs(bounds[0].x - calc.centerX),
calc.chartHeight / Math.abs(bounds[1].y - calc.centerY),
calc.chartHeight / Math.abs(bounds[0].y - calc.centerY)) / 2 : 1;
var texts = centerPoint.selectAll('.text')
.data(attrs.data.values);
var entered = texts.enter()
.append('text')
.attr('class', 'text')
entered
.attr("transform", function (d) {
return "translate(0,0)rotate( 0)";
})
.style("font-size", function (d) {
return 2 + "px";
})
.style("opacity", 1e-6)
texts = texts.merge(entered);
texts.attr("text-anchor", "middle")
.text(function (d) {
return d.text;
})
.style("fill", function (d) {
return scales.color(d.text.toLowerCase());
})
texts.transition()
.duration(1000)
.attr("transform", function (d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.style("font-size", function (d) {
return d.size + "px";
})
.style("opacity", 1)
.style("font-family", function (d) {
return d.font;
})
});
//add svg
var svg = patternify({ container: container, selector: 'svg-chart-container', elementTag: 'svg' })
svg.attr('width', attrs.svgWidth)
.attr('height', attrs.svgHeight)
// .attr("viewBox", "0 0 " + attrs.svgWidth + " " + attrs.svgHeight)
// .attr("preserveAspectRatio", "xMidYMid meet")
//add container g element
var chart = patternify({ container: svg, selector: 'chart', elementTag: 'g' })
chart.attr('transform', 'translate(' + (calc.chartLeftMargin) + ',' + calc.chartTopMargin + ')');
//add center point
var centerPoint = patternify({ container: chart, selector: 'center-point', elementTag: 'g' })
.attr('transform', `translate(${calc.centerX},${calc.centerY})`)
layouts.cloud.start();
// ################## EVENT LISTENERS ################
d3.select(window).on('resize.' + attrs.id, function () {
setDimensions();
redraw();
})
// smoothly handle data updating
updateData = function () {
}
//######################################### UTIL FUNCS ##################################
//enter exit update pattern principle
function patternify(params) {
var container = params.container;
var selector = params.selector;
var elementTag = params.elementTag;
var data = params.data || [selector];
if (!container) {
debugger;
}
// pattern in action
var selection = container.selectAll('.' + selector).data(data)
selection.exit().remove();
selection = selection.enter().append(elementTag).merge(selection)
selection.attr('class', selector);
return selection;
}
function setDimensions() {
var width = container.node().getBoundingClientRect().width;
main.svgWidth(width);
// if width is too small, change attrs.fontSize too e.t.c
}
function redraw() {
container.call(main);
}
function debug() {
if (attrs.isDebug) {
//stringify func
var stringified = scope + "";
// parse variable names
var groupVariables = stringified
//match var x-xx= {};
.match(/var\s+([\w])+\s*=\s*{\s*}/gi)
//match xxx
.map(d => d.match(/\s+\w*/gi).filter(s => s.trim()))
//get xxx
.map(v => v[0].trim())
//assign local variables to the scope
groupVariables.forEach(v => {
main['P_' + v] = eval(v)
})
}
}
debug();
});
};
//dinamic functions
Object.keys(attrs).forEach(key => {
// Attach variables to main function
return main[key] = function (_) {
var string = `attrs['${key}'] = _`;
if (!arguments.length) { return eval(` attrs['${key}'];`); }
eval(string);
return main;
};
});
//set attrs as property
main.attrs = attrs;
//debugging visuals
main.debug = function (isDebug) {
attrs.isDebug = isDebug;
if (isDebug) {
if (!window.charts) window.charts = [];
window.charts.push(main);
}
return main;
}
//exposed update functions
main.data = function (value) {
if (!arguments.length) return attrs.data;
attrs.data = value;
if (typeof updateData === 'function') {
updateData();
}
return main;
}
// run visual
main.run = function () {
d3.selectAll(attrs.container).call(main);
return main;
}
return main;
}
// missing from d3.v4 so we just copying from v3
// Copies a variable number of methods from source to target.
d3.rebind = function (target, source) {
var i = 1, n = arguments.length, method;
while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]);
return target;
};
// Method is assumed to be a standard D3 getter-setter:
// If passed with no arguments, gets the value.
// If passed with arguments, sets the value and returns the target.
function d3_rebind(target, source, method) {
return function () {
var value = method.apply(source, arguments);
return value === source ? target : value;
};
}
function d3_functor(v) {
return typeof v === "function" ? v : function () { return v; };
}
d3.functor = d3_functor;
</script>
</body>
[{"key":"და","value":8670483},{"key":"არ","value":3767689},{"key":"რომ","value":2586399},{"key":"რა","value":1869882},{"key":"თუ","value":1735775},{"key":"ეს","value":1428843},{"key":"უნდა","value":1240086},{"key":"მე","value":1191923},{"key":"ამ","value":1133752},{"key":"მაგრამ","value":987038},{"key":"არის","value":958995},{"key":"კი","value":918938},{"key":"არა","value":907085},{"key":"იყო","value":814109},{"key":"ვერ","value":761302},{"key":"ის","value":757457},{"key":"ან","value":653509},{"key":"ეგ","value":620925},{"key":"რო","value":605240},{"key":"ერთი","value":589008},{"key":"ს","value":560012},{"key":"რაც","value":539270},{"key":"მერე","value":538679},{"key":"ისე","value":527125},{"key":"შენ","value":478623},{"key":"როგორც","value":458847},{"key":"აქვს","value":457638},{"key":"აქ","value":429748},{"key":"ძალიან","value":424854},{"key":"სხვა","value":422943},{"key":"ჩემი","value":421896},{"key":"უფრო","value":417085},{"key":"არც","value":402073},{"key":"მაინც","value":399627},{"key":"დიდი","value":384253},{"key":"შეიძლება","value":383449},{"key":"ხო","value":372817},{"key":"იქნება","value":371651},{"key":"როგორ","value":359903},{"key":"ასე","value":359476},{"key":"ყველა","value":353031},{"key":"უკვე","value":339616},{"key":"ვიცი","value":337805},{"key":"იმ","value":334887},{"key":"რომელიც","value":332988},{"key":"კიდევ","value":332425},{"key":"ვარ","value":318228},{"key":"აი","value":318082},{"key":"იყოს","value":312963},{"key":"ნუ","value":299198},{"key":"ეხლა","value":296293},{"key":"მისი","value":293569},{"key":"ხომ","value":282707},{"key":"მაგ","value":282264},{"key":"ჯერ","value":281404},{"key":"რამე","value":279240},{"key":"რას","value":277107},{"key":"აბა","value":276167},{"key":"მინდა","value":275499},{"key":"მხოლოდ","value":275431},{"key":"ანუ","value":271518},{"key":"მარა","value":270009},{"key":"მაშინ","value":269330},{"key":"შემდეგ","value":267858},{"key":"მაქვს","value":263872},{"key":"ა","value":259570},{"key":"სულ","value":259319},{"key":"ერთ","value":256903},{"key":"კარგი","value":254748},{"key":"მეც","value":252669},{"key":"წლის","value":246383},{"key":"ხარ","value":245009},{"key":"საქართველოს","value":238956},{"key":"დროს","value":236144},{"key":"როცა","value":234250},{"key":"ახლა","value":231746},{"key":"არაა","value":226320},{"key":"მაგარი","value":225102},{"key":"რაღაც","value":224439},{"key":"კაი","value":220666},{"key":"ახალი","value":220226},{"key":"თან","value":213358},{"key":"ჩვენ","value":212324},{"key":"გინდა","value":210186},{"key":"აღარ","value":210044},{"key":"კიდე","value":207336},{"key":"თავის","value":206154},{"key":"შენი","value":205685},{"key":"დღეს","value":205098},{"key":"ყველაფერი","value":204904},{"key":"გილოცავ","value":204619},{"key":"ალბათ","value":202098},{"key":"ში","value":198842},{"key":"ამას","value":196630},{"key":"მარტო","value":194098},{"key":"ყველაზე","value":193261},{"key":"მეორე","value":191083},{"key":"ასეთი","value":191066},{"key":"სად","value":191057},{"key":"ზე","value":190618}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment