How to Make a Word Cloud in Python

Make a word cloud in Python with the wordcloud library, then control stopwords, shape, colors, and word frequencies.

To make a word cloud in Python, pass a string to WordCloud().generate(text) from the wordcloud library and show the result with Matplotlib's imshow(). Words that appear more often are drawn larger.

Install it with pip install wordcloud. The examples here use version 1.9.6.

Quick Example

This draws a word cloud of the US Constitution, read from a copy in the library's own GitHub repository.

from urllib.request import urlopen

import matplotlib.pyplot as plt
from wordcloud import WordCloud

url = ("https://raw.githubusercontent.com/amueller/word_cloud/"
       "93c5e4c/examples/constitution.txt")
text = urlopen(url).read().decode("utf-8")

wc = WordCloud(width=800, height=450, scale=1.5, background_color="white",
               colormap="viridis", max_words=150, random_state=42).generate(text)

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.imshow(wc, interpolation="bilinear")
ax.axis("off")
plt.show()

Word cloud of the US Constitution on a white background, with State, United States, Law, Congress, House and may among the largest words

The parameters worth knowing:

  • width and height set the canvas the words are laid out on, and scale=1.5 multiplies the output resolution, giving a 1200 x 675 image here.
  • background_color defaults to "black".
  • max_words defaults to 200.
  • random_state fixes the layout and colors. Without it, every run looks different.

Remove Stopwords from a Word Cloud

Common words such as "the", "of", and "shall" are removed by default using the built-in STOPWORDS set. Legal text has its own filler, like "may" and "Section", so add those to the set:

from wordcloud import STOPWORDS

my_stopwords = STOPWORDS | {"may", "one", "two", "section", "thereof", "article"}

wc = WordCloud(width=800, height=450, scale=1.5, background_color="white",
               colormap="viridis", stopwords=my_stopwords, max_words=150,
               random_state=42).generate(text)
wc.to_image()  # displays in a notebook

The same Constitution word cloud after removing may, section and other filler words, leaving State, United States, Law, Congress and House as the largest

Passing stopwords= replaces the default list, which is why the code combines it with STOPWORDS using |. Matching ignores case.

Check the Word Counts

process_text() returns the counts that determine the word sizes. It's the quickest way to find more stopwords:

import pandas as pd

freqs = WordCloud(stopwords=my_stopwords).process_text(text)
top = pd.Series(freqs).nlargest(15)
print(top.head())
State            66
United States    54
Law              34
Congress         29
House            28

"United States" is counted as one phrase because collocations=True is the default, which keeps pairs of words that occur together unusually often. Set collocations=False to count single words only. "State" then rises from 66 to 129, because it picks up the occurrences that were part of phrases.

Plurals are also merged by default (normalize_plurals=True), so "State" and "States" share a count.

Make a Word Cloud in a Custom Shape

The mask parameter takes a NumPy array. Words are placed everywhere except the pure white (255) pixels. You can draw a circle with NumPy:

import numpy as np

size = 800
y, x = np.ogrid[:size, :size]
outside = (x - size / 2) ** 2 + (y - size / 2) ** 2 > (size / 2 - 10) ** 2
mask = np.where(outside, 255, 0).astype(np.uint8)

wc = WordCloud(mask=mask, background_color="white", colormap="cividis",
               stopwords=my_stopwords, contour_width=4, contour_color="#1d3557",
               random_state=42).generate(text)
wc.to_image()

Circular word cloud of the US Constitution with a navy outline

When a mask is set, its dimensions replace width and height.

To use your own silhouette, load a black shape on a white background:

from PIL import Image

mask = np.array(Image.open("shape.png").convert("L"))

If your image has a transparent background, paste it onto a white one first. Converting to grayscale drops the alpha channel, and transparent pixels are often stored as black, so words would fill the wrong area.

Change Word Cloud Colors

colormap accepts any Matplotlib colormap. For full control, pass a color_func that returns a color for each word. This one picks random shades of a single red:

def shades_of_red(word, font_size, random_state=None, **kwargs):
    lightness = random_state.randint(25, 55)
    return f"hsl(355, 70%, {lightness}%)"


wc = WordCloud(width=800, height=450, scale=1.5, background_color="#fdf6ec",
               color_func=shades_of_red, stopwords=my_stopwords,
               prefer_horizontal=1.0, max_words=80, random_state=7).generate(text)
wc.to_image()

Word cloud in shades of red on a cream background with every word horizontal

prefer_horizontal=1.0 also stops words from being rotated, which makes the cloud easier to read.

To restyle an existing cloud without recomputing the layout, call wc.recolor(colormap="magma", random_state=1).

Word Cloud from Frequencies or a DataFrame

If you already have a weight per word, use generate_from_frequencies() with a dictionary. This sizes US state names by their 2025 population estimate from the Census Bureau:

url = ("https://www2.census.gov/programs-surveys/popest/datasets/"
       "2020-2025/state/totals/NST-EST2025-ALLDATA.csv")
pop = pd.read_csv(url)

# SUMLEV 40 is the state level, which includes DC and Puerto Rico
states = pop[(pop["SUMLEV"] == 40) & (pop["NAME"] != "Puerto Rico")]
weights = dict(zip(states["NAME"], states["POPESTIMATE2025"]))

wc = WordCloud(width=800, height=450, scale=1.5, background_color="#0b132b",
               colormap="summer", relative_scaling=0.7, max_font_size=90,
               random_state=3).generate_from_frequencies(weights)
wc.to_image()

Word cloud of US state names sized by 2025 population on a dark navy background, led by California, Texas, Florida and New York

California (39.4 million), Texas (31.7 million), and Florida (23.5 million) are the largest names. Stopwords are ignored with this method, so filter the dictionary yourself.

relative_scaling controls how closely font size follows the weights. At 1, a word with twice the weight is twice the size. At 0, only the rank order matters. Lower values, along with a smaller max_font_size, help small words fit: wc.layout_ lists the words that were actually drawn.

Save a Word Cloud as PNG or SVG

wc.to_file("wordcloud.png")

with open("wordcloud.svg", "w", encoding="utf-8") as f:
    f.write(wc.to_svg())

to_file() writes the image at full resolution, which is sharper than saving the Matplotlib figure. For a transparent background, create the cloud with mode="RGBA" and background_color=None.

Word Cloud vs Bar Chart

Word clouds give a quick impression of a text, but they're poor for comparing values. Long words take more space than short ones, and color usually means nothing. When the counts matter, plot them as a horizontal bar chart:

fig, ax = plt.subplots(figsize=(8, 5))
bars = ax.barh(top.index[::-1], top.values[::-1], color="#457b9d")
ax.bar_label(bars, padding=3)
ax.spines[["top", "right", "bottom"]].set_visible(False)
ax.set_xticks([])
ax.set_title("Most frequent words in the US Constitution", loc="left")
fig.tight_layout()
plt.show()

Horizontal bar chart of the 15 most frequent words in the US Constitution: State 66, United States 54, Law 34, Congress 29, House 28 and so on down to Constitution 14

Use When
Word cloud A cover image, a slide, or a first look at what a body of text is about
Bar chart Readers need to compare or rank the counts

Similar Topics