How to Create Beautiful Word Cloud in Python
A word cloud is a powerful visualization tool that highlights the most frequent words in text data. Using shaped word clouds, such as a parrot, makes visualizations more engaging and aesthetically appealing.
Why Use a Shaped Word Cloud?
- Enhances visual appeal by following an image shape
- Helps in branding and creative presentations
- Allows for custom color mapping from the original image
- Useful for text analysis, marketing, and education
When to Use a Word Cloud
- Provides a quick visual summary of text data
- Highlights important keywords in large datasets
- Useful for NLP tasks, sentiment analysis, and reports
- Creates engaging visualizations for presentations
Steps to Create a Parrot-Shaped Word Cloud
- Import required libraries (
wordcloud
,matplotlib
,numpy
,PIL
) - Load a custom mask image (parrot shape example)
- Extract colors from the image using
ImageColorGenerator
- Process text (remove stopwords, clean words)
- Generate a WordCloud using the mask and color mapping
- Display the final word cloud
More examples and inspiration: WordCloud Examples
Example: Parrot-Shaped Word Cloud
import os
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_gradient_magnitude
from wordcloud import WordCloud, ImageColorGenerator
d = os.path.dirname(__file__) if "__file__" in locals() else os.getcwd()
text = open(os.path.join(d, '/home/user/wiki_rainbow.txt'), encoding="utf-8").read()
parrot_color = np.array(Image.open(os.path.join(d, "/home/user/parrot-by-jose-mari-gimenez2.jpg")))
parrot_color = parrot_color[::3, ::3]
parrot_mask = parrot_color.copy()
parrot_mask[parrot_mask.sum(axis=2) == 0] = 255
edges = np.mean([gaussian_gradient_magnitude(parrot_color[:, :, i] / 255., 2) for i in range(3)], axis=0)
parrot_mask[edges > .08] = 255
wc = WordCloud(max_words=2000, mask=parrot_mask, max_font_size=40, random_state=42, relative_scaling=0)
wc.generate(text)
plt.imshow(wc)
image_colors = ImageColorGenerator(parrot_color)
wc.recolor(color_func=image_colors)
plt.figure(figsize=(10, 10))
plt.imshow(wc, interpolation="bilinear")
wc.to_file("parrot_new.png")
Original source code and explanations can be found here: word_cloud examples parrot.py
You need to download to run the code above:
Output
A parrot-shaped word cloud where words are colored based on the original parrot image:
Full size result:
Customizations
You can enhance your word cloud with:
- Change the shape:
wordcloud = WordCloud(mask=custom_mask, contour_color='black', contour_width=2)
- Custom fonts:
WordCloud(font_path='path/to/font.ttf')
- Increase max words & adjust size:
WordCloud(max_words=200, width=1000, height=500, contour_width=2)
- Use different color maps:
WordCloud(colormap='plasma') # Try 'cool', 'magma', 'inferno', etc.
Resources
Shaped word clouds create stunning visualizations for presentations, reports, and branding.