Generate Word Count Histogram for Text

  • Share this:

Code introduction


The function takes a text as input and generates a word count histogram using the matplotlib library, showing the 20 most common words and their frequencies in the text.


Technology Stack : matplotlib, Counter, datetime, collections

Code Type : Custom function

Code Difficulty : Intermediate


                
                    
import random
from datetime import datetime
from collections import Counter
import matplotlib.pyplot as plt

def generate_random_word_count_chart(text):
    """
    Generate a word count chart from a given text using matplotlib.
    """
    # Split the text into words
    words = text.split()
    
    # Count the occurrences of each word
    word_counts = Counter(words)
    
    # Sort the words by frequency
    sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
    
    # Extract the top 20 most frequent words
    top_words = sorted_word_counts[:20]
    
    # Extract the words and their counts
    labels, counts = zip(*top_words)
    
    # Plotting
    fig, ax = plt.subplots()
    ax.bar(labels, counts)
    ax.set_xlabel('Words')
    ax.set_ylabel('Count')
    ax.set_title('Top 20 Most Frequent Words')
    
    # Display the plot
    plt.show()

# Example usage
sample_text = "This is a sample text. This text is used to demonstrate the word count chart function."
generate_random_word_count_chart(sample_text)