$ pip install wordcloud★Pulls innumpy,pillow&matplotlib.from wordcloud import WordCloud★Everything lives on this one class.from wordcloud import STOPWORDS, ImageColorGeneratorBuilt-in stopword set & image-based colouring.import matplotlib.pyplot as pltTo display the result inline.from PIL import Image; import numpy as npNeeded only when using a mask image.
WordCloud().generate(text)★From a raw string — counts words for you.WordCloud().generate_from_frequencies(freq)★From a{word: count}dict you already have.wc = WordCloud(width=800, height=400, background_color="white")★Options go in the constructor, not the method.wc.generate(text)Returns theWordCloudobject (chainable).# build once → recolor / export many timesLayout is the expensive step; reuse it.
.generate(text)★Tokenize + count + lay out, all at once..generate_from_frequencies({"data": 40, "code": 25})Skip tokenizing — you supply the counts..process_text(text)Just the tokenizer → a frequency dict..fit_words(freq)Alias ofgenerate_from_frequencies.from collections import CounterCounter(words)makes a ready freq dict.df["col"].value_counts().to_dict()Pandas counts → feed straight in.
width=800, height=400★Canvas size in px (default 400×200).background_color="white"★Default is"black".mode="RGBA", background_color=NoneTransparent background.scale=2Render bigger — faster than doubling width/height.max_words=200★Cap how many words appear.margin=2Pixels of space around each word.
relative_scaling=0.5★0 = size by rank · 1 = size ∝ frequency · auto=0.5.max_font_size=100Cap the largest word (default: image height).min_font_size=4Stop once words get this small.font_step=1Bigger step = faster, coarser fit.font_path="path/to/font.ttf"Any OTF/TTF; default is bundled DroidSansMono.
prefer_horizontal=0.9★Fraction of words tried horizontally first.prefer_horizontal=1.0Keep every word horizontal.random_state=42★Fix the layout so it's reproducible.repeat=TrueRepeat words until the canvas fills.# placement = spiral pack, largest firstEach word avoids the ones already placed.
collocations=True★Keep bigrams like"machine learning"(default).collocations=FalseTurn off — avoids near-duplicate pairs.collocation_threshold=30Higher = fewer bigrams kept.regexp=r"\w[\w']+"Custom token pattern (the default shown).normalize_plurals=TrueMerge"cat"/"cats"(keeps the singular).include_numbers=FalseDrop pure numbers (set True to keep).min_word_length=3Ignore words shorter than this.
from wordcloud import STOPWORDS★The built-in set (used whenstopwords=None).stopwords=STOPWORDS.union({"said", "one"})★Extend the defaults with your own.stopwords=set(["a", "the", "of"])Replace the list entirely.generate_from_frequencies(..)noteIgnores stopwords, collocations & regexp.
colormap="viridis"★The default; any matplotlib colormap works.colormap="magma" · "tab10" · "Blues"Sequential, categorical, single-hue…random_state=1Fix which colours get drawn.wc.recolor(colormap="plasma")★Re-colour without re-running layout (fast).wc.recolor(random_state=3)Same words, fresh colour draw.
color_func=lambda *a, **k: "steelblue"★One solid colour for every word.color_func=my_fnOverridescolormapentirely.# signature Vega gives your function:word, font_size, position, orientation, font_path, random_statefrom wordcloud import get_single_color_funcOne hue, varied brightness per word.ImageColorGenerator(img_array)★Take each word's colour from a source image.wc.recolor(color_func=ImageColorGenerator(img))The classic "colour from the mask" trick.
mask = np.array(Image.open("shape.png"))★Load a shape as a numpy array.WordCloud(mask=mask)★Words fill the shape; overrides width/height.# white (255) = masked OUTgotchaNon-white pixels are where words may go.contour_width=1, contour_color="steelblue"Trace the mask's outline.ImageColorGenerator(mask)Recolour words to match the mask image.
wc.to_file("cloud.png")★Save straight to an image file.wc.to_image()Return a PILImage.wc.to_array()Return a numpy array (H×W×3).wc.to_svg()Scalable vector output.wc.to_svg(embed_font=True)Self-contained SVG (font baked in).
plt.imshow(wc, interpolation="bilinear")★bilinearsmooths the rendered words.plt.axis("off")★Hide the axes & ticks.plt.figure(figsize=(10, 5))Set the display size beforeimshow.plt.savefig("out.png", dpi=300, bbox_inches="tight")Save the figure (with any contour/title).plt.show()Render it.
$ wordcloud_cli --text in.txt --imagefile out.png★The whole thing from a shell.$ wordcloud_cli --helpFlags mirror the constructor params.$ pdftotext doc.pdf - | wordcloud_cli --imagefile wc.pngPipe a PDF's text straight in.$ ... --mask shape.png --contour_width 1Masks work from the CLI too.
column: .generate(" ".join(df["text"]))Join a text column into one string.counts: .generate_from_frequencies(counter)ACounteror value_counts dict.transparent: mode="RGBA", background_color=NonePNG that drops onto any background.single hue: color_func=lambda *a,**k: "white"On a dark background → clean monochrome.shaped + coloured: mask + ImageColorGeneratorWords in a shape, coloured by that image.reproducible: random_state=42Same layout & colours every run.
wc.words_{word: normalized_freq}after generating.wc.layout_Per word:(text, size, (x,y), orient, colour).len(wc.words_)How many words were actually kept.wc.generate(t) vs wc.recolor()Re-layout (slow) vs re-colour (fast).deps: numpy · pillow · matplotlibPulled in automatically by pip.