Python Creates Word Cloud Image: A Step Guide – Python Wordcloud Tutorial

By | October 12, 2020

In this tutorial, we will use an example to show you how to create a word cloud in python. You can learn how to do step by step.

Install python wordcloud package

You can use pip to install wordcloud.

pip install wordcloud

After having installed wordcloud, we can use it to create a word cloud image.

Import library

from wordcloud import WordCloud

We can create a WordCloud instance to create a word cloud image.

Create WordCloud instance

wc = WordCloud(background_color='white', width = 300, height=300, margin=2)

WordCloud class is defined as:

        def __init__(self, font_path=None, width=400, height=200, margin=2,
                 ranks_only=None, prefer_horizontal=.9, mask=None, scale=1,
                 color_func=None, max_words=200, min_font_size=4,
                 stopwords=None, random_state=None, background_color='black',
                 max_font_size=None, font_step=1, mode="RGB",
                 relative_scaling='auto', regexp=None, collocations=True,
                 colormap=None, normalize_plurals=True, contour_width=0,
                 contour_color='black', repeat=False,
                 include_numbers=False, min_word_length=0, collocation_threshold=30):

We can find some important parameters.

font_path: You can set a font to create a word cloud image.

max_words: How many words in word cloud image.

background_color: The backgroud color of word cloud image.

Create a word cloud image

We will create a word cloud image based on text.

text = 'In this tutorial, we will use an example to show you how to create a word cloud in python. You can learn how to do step by step.Install python wordcloud package You can use pip to install wordcloud.'

wc.generate(text)

wc.to_file('wc.png')

We will use wc.generate() function to create a word cloud data, then use wc.to_file() to save it to an image.

The word cloud image is:

Python Creates Word Cloud - A Step Guide - Python Wordcloud Tutorial

Why are the font size of some words bigger than others?

Python wordcloud will change the font size of word by its frequency in text. the frequency is larger, the font size is bigger.

Leave a Reply

Your email address will not be published. Required fields are marked *