Masked wordcloudΒΆ

Using a mask you can generate wordclouds in arbitrary shapes.

  • masked
  • masked
from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import os

from wordcloud import WordCloud, STOPWORDS

# get data directory (using getcwd() is needed to support running example in generated IPython notebook)
d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()

# Read the whole text.
text = open(path.join(d, 'alice.txt')).read()

# read the mask image
# taken from
alice_mask = np.array(, "alice_mask.png")))

stopwords = set(STOPWORDS)

wc = WordCloud(background_color="white", max_words=2000, mask=alice_mask,
               stopwords=stopwords, contour_width=3, contour_color='steelblue')

# generate word cloud

# store to file
wc.to_file(path.join(d, "alice.png"))

# show
plt.imshow(wc, interpolation='bilinear')
plt.imshow(alice_mask,, interpolation='bilinear')

Total running time of the script: ( 0 minutes 9.916 seconds)

Gallery generated by Sphinx-Gallery