Public
Edited
Oct 16, 2022
Fork of Word cloud
Insert cell
Insert cell
Insert cell
Insert cell
medio.id
Insert cell
Insert cell
Insert cell
Insert cell
function WordCloud(
text,
{
size = (group) => group.length, // Given a grouping of words, returns the size factor for that word
word = (d) => d, // Given an item of the data array, returns the word
marginTop = 0, // top margin, in pixels
marginRight = 0, // right margin, in pixels
marginBottom = 0, // bottom margin, in pixels
marginLeft = 0, // left margin, in pixels
width = 640, // outer width, in pixels
height = 400, // outer height, in pixels
maxWords = 250, // maximum number of words to extract from the text
fontFamily = "sans-serif", // font family
fontScale = 15, // base font size
padding = 0, // amount of padding between the words (in pixels)
rotate = 0, // a constant or function to rotate the words
invalidation // when this promise resolves, stop the simulation
} = {}
) {
const words =
typeof text === "string" ? text.split(/\W+/g) : Array.from(text);

const data = d3
.rollups(words, size, (w) => w)
.sort(([, a], [, b]) => d3.descending(a, b))
.slice(0, maxWords)
.map(([key, size]) => ({ text: word(key), size }));

const svg = d3
.create("svg")
.attr("viewBox", [0, 0, width, height])
.attr("width", width)
.attr("font-family", fontFamily)
.attr("text-anchor", "middle")
.attr("style", "max-width: 100%; height: auto; height: intrinsic;");

const g = svg
.append("g")
.attr("transform", `translate(${marginLeft},${marginTop})`);

function handleClick(d, i) {
var e = d3.select(this);
console.log(e.text());
}

function handleMouseOver(d, i) {
d3.select(this)
.classed("word-hovered", true)
.transition(`mouseover-${text}`)
.duration(200)
.ease(d3.easeLinear)
// .attr("font-size", size + 2)
.attr("font-weight", "bold");
}

function handleMouseOut(d, i) {
d3.select(this)
.classed("word-hovered", false)
.interrupt(`mouseover-${text}`)
.attr("font-size", size);
}

const cloud = d3Cloud()
.size([width - marginLeft - marginRight, height - marginTop - marginBottom])
.words(data)
.padding(padding)
.rotate(rotate)
.font(fontFamily)
.fontSize((d) => Math.sqrt(d.size) * fontScale)
.on("word", ({ size, x, y, rotate, text }) => {
g.append("text")
.attr("font-size", size)
.attr("transform", `translate(${x},${y}) rotate(${rotate})`)
.text(text)
.classed("click-only-text", true)
.classed("word-default", true)
.on("mouseover", handleMouseOver)
.on("mouseout", handleMouseOut)
.on("click", handleClick);
});

cloud.start();
invalidation && invalidation.then(() => cloud.stop());
return svg.node();
}
Insert cell
words = text
.split(/[\s.]+/g)
.map((w) => w.replace(/^[“‘"\-—()\[\]{}]+/g, ""))
.map((w) => w.replace(/[;:.!?()\[\]{},"'’”\-—]+$/g, ""))
.map((w) => w.replace(/['’]s$/g, ""))
.map((w) => w.substring(0, 30))
.map((w) => w.toLowerCase())
.filter((w) => w && !stopwords.has(w))
Insert cell
words.filter(w => /\W/.test(w))
Insert cell
stopwords = new Set(
"a,al,algo,algunas,algunos,ante,antes,como,con,contra,cual,cuando,de,del,desde,donde,durante,e,el,ella,ellas,ellos,en,entre,era,erais,eran,eras,eres,es,esa,esas,ese,eso,esos,esta,estaba,estabais,estaban,estabas,estad,estada,estadas,estado,estados,estamos,estando,estar,estaremos,estará,estarán,estarás,estaré,estaréis,estaría,estaríais,estaríamos,estarían,estarías,estas,este,estemos,esto,estos,estoy,estuve,estuviera,estuvierais,estuvieran,estuvieras,estuvieron,estuviese,estuvieseis,estuviesen,estuvieses,estuvimos,estuviste,estuvisteis,estuviéramos,estuviésemos,estuvo,está,estábamos,estáis,están,estás,esté,estéis,estén,estés,fue,fuera,fuerais,fueran,fueras,fueron,fuese,fueseis,fuesen,fueses,fui,fuimos,fuiste,fuisteis,fuéramos,fuésemos,ha,habida,habidas,habido,habidos,habiendo,habremos,habrá,habrán,habrás,habré,habréis,habría,habríais,habríamos,habrían,habrías,habéis,había,habíais,habíamos,habían,habías,han,has,hasta,hay,haya,hayamos,hayan,hayas,hayáis,he,hemos,hube,hubiera,hubierais,hubieran,hubieras,hubieron,hubiese,hubieseis,hubiesen,hubieses,hubimos,hubiste,hubisteis,hubiéramos,hubiésemos,hubo,la,las,le,les,lo,los,me,mi,mis,mucho,muchos,muy,más,mí,mía,mías,mío,míos,nada,ni,no,nos,nosotras,nosotros,nuestra,nuestras,nuestro,nuestros,o,os,otra,otras,otro,otros,para,pero,poco,por,porque,que,quien,quienes,qué,se,sea,seamos,sean,seas,sentid,sentida,sentidas,sentido,sentidos,seremos,será,serán,serás,seré,seréis,sería,seríais,seríamos,serían,serías,seáis,siente,sin,sintiendo,sobre,sois,somos,son,soy,su,sus,suya,suyas,suyo,suyos,sí,también,tanto,te,tendremos,tendrá,tendrán,tendrás,tendré,tendréis,tendría,tendríais,tendríamos,tendrían,tendrías,tened,tenemos,tenga,tengamos,tengan,tengas,tengo,tengáis,tenida,tenidas,tenido,tenidos,teniendo,tenéis,tenía,teníais,teníamos,tenían,tenías,ti,tiene,tienen,tienes,todo,todos,tu,tus,tuve,tuviera,tuvierais,tuvieran,tuvieras,tuvieron,tuviese,tuvieseis,tuviesen,tuvieses,tuvimos,tuviste,tuvisteis,tuviéramos,tuviésemos,tuvo,tuya,tuyas,tuyo,tuyos,tú,un,una,uno,unos,vosotras,vosotros,vuestra,vuestras,vuestro,vuestros,y,ya,yo,él,éramos".split(
","
)
)
Insert cell
WordCloud("Esto es una prueba", {
width: 250,
height: 100,
size: () => 0.3 + Math.random(),
rotate: () => (~~(Math.random() * 6) - 3) * 30
})
Insert cell
d3Cloud = require("d3-cloud@1")
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more