Public
Edited
Nov 29, 2023
Paused
Insert cell
Insert cell
d3Cloud = require("d3-cloud@1")
Insert cell
Insert cell
array_of_lyrics = data.map( (d) => d.lyric);
Insert cell
taylor_swift_lyrics.csv
Type Table, then Shift-Enter. Ctrl-space for more options.

Insert cell
Insert cell
// for each lyric array (Ex: "To see me like that")
array_of_lyrics.forEach(
// split it into each word
(lyricArray) => {
let listOfEachWord = lyricArray.split(" ")
listOfEachWord.forEach( (word) =>
array_of_words.push(word))
}
)
Insert cell
array_of_words = []
Insert cell
Insert cell
concatenated_string = array_of_words.join(' ')
Insert cell
Insert cell
function WordCloud(text, { // takes as input the text, in the form of a string
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
width = 640, // outer width, in pixels
height = 400, // outer height, in pixels
maxWords = 300, // 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) // getting a sum of the words, and finding the ones with the most occurances
.filter(([key, size]) => key.length > 4) // Filter words with length greater than 1
.sort(([, a], [, b]) => d3.descending(a, b))
.slice(0, maxWords)
.map(([key, size]) => ({text: word(key), size}));
const svg = d3.create("svg") // creating the svg elements (the words)
.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 cloud = d3Cloud()
.size([width, height])
.words(data)
.padding(padding)
.rotate(rotate)
.font(fontFamily)
.fontSize(d => Math.sqrt(d.size) * fontScale)
.on("word", ({size, x, y, rotate, text}) => {
svg.append("text")
.attr("font-size", size)
.attr("transform", `translate(${x},${y}) rotate(${rotate})`)
.style("fill",function() {
return "hsl(" + Math.random() * 360 + ",100%,50%)";
})
.text(text);
});

cloud.start();
invalidation && invalidation.then(() => cloud.stop());
return svg.node();
}
Insert cell
WordCloud(concatenated_string, {
width: 1500,
height: 1500,
invalidation // a promise to stop the simulation when the cell is re-run
})
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