top of page

Welcome
to NumpyNinja Blogs

NumpyNinja: Blogs. Demystifying Tech,

One Blog at a Time.
Millions of views. 

How to Generate a Word Cloud Visualization in Python with Ease

Jan 24, 2025
4 min read

Creating a Word Cloud Visualization in Python

Word clouds are an excellent way to visualize textual data. They display words in varying sizes, with the size of each word representing its frequency in the dataset. In this tutorial, we’ll show you how to create a word cloud using Python and the WordCloud library, with a simple example centered around sports data.


The Dataset

For this example, let’s assume we’re working with a dataset of athletes. The dataset contains a column named sport, which lists the sport associated with each athlete. We’ll use this column to generate a word cloud.

Here’s a quick summary of the steps we’ll follow:

  1. Combine all the text values from the sport column into a single string.

  2. Use the WordCloud library to generate the word cloud.

  3. Customize the appearance and display it using matplotlib.


Step-by-Step Implementation


Step 1: Install Required Libraries

Before starting, ensure you have the required libraries installed. You can install them using pip:

Step 2: Import Libraries

Step 3: Prepare the text

First, we will extract all the values from the sport column and combine them into a single string. This allows the word cloud to analyze the frequency of each word.

# Combine all text from the 'sport' column into a single string

data_Combined = ' '.join(Athletes['sport'])


Step 4: Generate the Word Cloud

Next, we use the WordCloud class to create the visualization. The WordCloud class is highly versatile and provides several parameters to customize the generated word cloud. Below is a detailed explanation of some of its key attributes:


  • width: Sets the width of the output image in pixels. Default is 400.

  • height: Sets the height of the output image in pixels. Default is 200.

  • background_color: Defines the background color of the word cloud. Popular options include white and black.

  • max_words: Limits the number of words displayed in the word cloud. Default is 200.

  • stopwords: Excludes common words (e.g., "and", "the", "in") from the visualization. A predefined set of stopwords is available in wordcloud.STOPWORDS, but you can also provide your own.

  • colormap: Specifies the color scheme of the words. Options include viridis, plasma, inferno, and more.

  • font_path: Allows you to set a custom font for the word cloud. If not specified, it uses the default system font.


Here’s how we can use these attributes in our example:


from wordcloud import WordCloud

import matplotlib.pyplot as plt

 

# Create a word cloud

word_Cloud = WordCloud(

    width=800,

    height=400,

    background_color='black',

    max_words=150,

    colormap='coolwarm'

).generate(data_Combined)


Step 5: Display the Word Cloud

Finally, we use the matplotlib library to display the word cloud. The imshow function renders the image, and we turn off the axes using plt.axis('off') for a cleaner look.


# Plot the word cloud

plt.figure(figsize=(10, 5))

plt.imshow(word_Cloud, interpolation='bilinear')

plt.axis('off')  # Hide the axes


Complete Code

Here’s the complete Python script:

from wordcloud import WordCloud

import matplotlib.pyplot as plt

 

# Combine all text from the 'sport' column into a single string

data_Combined = ' '.join(Athletes['sport'])

 

# Create a word cloud

word_Cloud = WordCloud(

    width=800,

    height=400,

    background_color='black',

    max_words=150,

    colormap='coolwarm'

).generate(data_Combined)

 

# Plot the word cloud

plt.figure(figsize=(10, 5))

plt.imshow(word_Cloud, interpolation='bilinear')

plt.axis('off')  # Hide the axes


Output:



How to change the Word Cloud Shape???

We can use the mask parameter to shape a word cloud . Here's a quick overview of how you can create a shaped word cloud using Python and the wordcloud library. For this,I am assuming a random data and try to display it in the shape of USA map .


!pip install requests

from wordcloud import WordCloud

import matplotlib.pyplot as plt

 

from PIL import Image

import numpy as np

from io import BytesIO

 

usa_mask = np.array(Image.open(r"C:\Users......\Desktop\USA.png"))

 

# Example text data

text_data = [

    "Basketball is a popular sport played around the world",

    "Tennis is a fast-paced game with great athletic demands",

    "Cricket is a widely followed sport, especially in England and India",

    "**Soccer** is the most popular sport globally, with millions of fans",

    "Baseball is a traditional American sport with a rich history",

    "Rugby is known for its physicality and strategy",

    "Hockey is a fast-paced sport played on ice",

    "Swimming is a great individual sport with global competitions",

    "Soccer", "Soccer", "Soccer", "Soccer", "Soccer", "Soccer", "Soccer", "Soccer", "Soccer", "Hockey", "Hockey", "Hockey",  "Hockey", "Rugby",  "Rugby", "Rugby", "Rugby", "Rugby", "Rugby", "Rugby", "Rugby", "Rugby"]

 

# Combine all text into a single string

data_combined = ' '.join(text_data)

 

# Generate the word cloud

word_cloud = WordCloud(

    width=800,

    height=400,

    background_color='white',

    colormap='viridis',

    mask=usa_mask,  # Apply the USA map mask

    contour_width=3,  # Outline width

    contour_color='purple'  # Outline color

).generate(data_combined)

 

# Display the word cloud

plt.figure(figsize=(10, 5))

plt.imshow(word_cloud, interpolation='bilinear')

plt.axis('off')  # Hide the axes


Output:


Key Takeaways

  • Customization: The WordCloud library offers numerous customization options, such as specifying fonts, color schemes, and stopwords (words to exclude from the visualization).

  • Insights: Word clouds provide an intuitive way to identify the most frequent words in your dataset at a glance.

  • Use Cases: They are particularly useful for text analysis tasks like exploring survey responses, social media data, or any other large text-based dataset.


With just a few lines of code, you can create compelling visualizations to complement your data analysis. Try experimenting with different datasets and customization options to make your word clouds even more impactful.

 
 

+1 (302) 200-8320

NumPy_Ninja_Logo (1).png

Numpy Ninja Inc. 8 The Grn Ste A Dover, DE 19901

© Copyright 2025 by Numpy Ninja Inc.

  • Twitter
  • LinkedIn
bottom of page