Code

Programming a Beautiful Word Cloud in Python

Programming a Beautiful Word Cloud in Python

Free Python Course ➞ Mini-course for beginners and experienced coders. 4 cool projects in the portfolio, live communication with the speaker. Click and find out what you can learn in the course.

Learn more

When things are unclear, a data scientist resorts to data visualization. This process significantly simplifies the identification of insights and helps formulate hypotheses for further testing. Data visualization is an essential tool in analytics, allowing for a better understanding of the structure and relationships in data, which in turn facilitates more informed decisions.

A word cloud is an effective tool for visualizing text data, combining exploratory analysis, infographics, and data design. This method allows for a quick overview of large, loosely structured texts, including fiction, scientific, and informational materials. Using a word cloud helps highlight key terms and ideas, making it a valuable tool for data analysis and information retrieval.

A word cloud is a powerful tool that helps visualize data and present information in a compact and clear format. Key reasons for using a word cloud include its ability to quickly convey key ideas and themes, improve information comprehension, and simplify text analysis. Furthermore, word clouds help identify the most frequently used terms, which can be useful for SEO and content marketing. Using word clouds also helps increase audience engagement, allowing users to navigate content more quickly and identify important aspects. Thus, word clouds are an effective tool for both data analysis and information visualization, making them useful for a variety of fields, from education to business.

  • Firstly, it's beautiful—a successful visualization enhances a portfolio.
  • Secondly, the word cloud shows the most popular words in the text, which is useful for quickly evaluating it. For example, for a school essay or a conversational text, these may be filler words (it would be a good idea to get rid of these), while for scientific or "info-style" texts, these may be words more relevant to the content.
  • Thirdly, creating such a visualization is not at all difficult—and you'll see for yourself now.

We'll be using Google Colab for our work, which allows you to write code directly in the browser. The code will be written in Python, and we'll get the text data from Wikipedia. If you encounter any difficulties, you can always refer to our notebook; all necessary links will be provided at the end of the article.

Getting Started

To get started with Google Colab, simply log in to your Gmail account and open the Welcome Notebook in your browser. It is also recommended to read several articles that will help you better understand the capabilities of Colab and learn the basics of Python needed for data scientists.

After launching Google Colab, you need to install the library for working with Wikipedia, as well as the stop-words library, which includes lists of stop words for text analysis in various languages. Installing these libraries will allow you to efficiently process and analyze text data using Wikipedia resources and filtering out insignificant words.

Run each command in a separate code cell. This approach makes it easier to track the results of execution and allows you to quickly identify possible errors.

A simple word cloud

Of course, provide the input text to be processed.

In this project, we imported the newly installed Wikipedia library and the re library for working with regular expressions. Next, we specified the Wikipedia language and stored the name of the page of interest in the wiki variable. You can use any other page of your choice for further work.

The text content of the page was placed in the text variable. Then, using regular expressions, we removed unnecessary characters, such as punctuation marks, paragraph breaks, and extra separators. This process allows us to optimize the text for further processing and improves its readability. Regular expressions are an effective tool for cleaning data, which is especially important in the context of SEO. Clean text improves the information's readability for users and search engines, which in turn can positively impact a page's ranking in search results.

Now we need a library and a function for text visualization. We'll import the library and create the function ourselves, as it will be useful later.

The %matplotlib inline command displays graphs directly in a Google Colab notebook. This allows you to conveniently visualize data and analysis results without having to open separate graph windows, greatly simplifying the process of working with interactive visualizations. Using this command makes working with the Matplotlib library more efficient and visual, as graphs appear in the same document as the code, providing easy access to analysis results.

The plot_cloud function visualizes a word cloud. It takes a word cloud as a parameter, sets the image size in inches, and displays it on the screen. The axis method with the "off" argument disables the display of axis labels, allowing you to focus on the word cloud itself without being distracted by additional elements.

You're almost done, just finishing the final preparations.

To add your own stop words to the STOPWORDS_RU variable, use the .add("new stop word") method. This method allows you to effectively expand the list of stop words, which helps improve text processing and enhance the quality of data analysis. Make sure you add only those words that are truly irrelevant to your task to optimize your results.

The random_state=1 parameter ensures reproducibility of results. If this parameter is not set, the word cloud will be different each time the function is run, which may complicate analysis and comparison of results. Setting a fixed value for random_state allows for consistent visualizations across multiple code runs, which is especially useful for scientific research and presentations.

The collocations parameter controls whether two-word combinations, known as bigrams, are included in the final visualization. In the current settings, this parameter is disabled, meaning that two-word phrases will not be displayed in the word cloud. To obtain a more diverse and informative word cloud, it is recommended to enable the use of bigrams.

Save the created image to a file. This will allow you to save the results of your work and use them in the future. Correctly saving images is important to ensure their quality and accessibility. Choose the appropriate file format that meets your requirements, be it JPEG, PNG, or another. After that, specify the file name and save location. Make sure you save the image at the desired resolution to ensure it retains all the details and is ready for use.

You can find the file in the Files menu on the left and download it.

Complex Word Cloud

To create a complex word cloud other than a simple rectangular one, you need to use an image. Ideally, a black and white image with high contrast and a minimum of small details. This will ensure clarity and expressiveness of the cloud shape, which is especially important for visual perception.

I downloaded an image called upvote.png. You can do the same. After downloading, simply drag it to the list of files and folders located on the left in your text editor.

We imported the NumPy library and the Image function from the PIL (Python Imaging Library) library. Using these tools, we load the image from the file and convert it into a mask (the mask variable), which will be used to create the word cloud. This approach allows for the effective visualization of text information using graphic elements.

Note that the mask parameter is now available in the WordCloud() function. This parameter allows you to specify the shape of the word cloud, significantly expanding the possibilities for text visualization. Using mask helps create a unique and attractive word cloud design that can better convey the essence of the information being presented. Customizing the mask in WordCloud() is an important step to increasing the aesthetic value and information content of your graphs.

Here's the result of our latest project: