How to Make a Twitter (X) Word Cloud from Tweets in Python

- Pipeline: fetch tweets (
/twitter/user/last_tweetsfor an account,/twitter/tweet/advanced_searchfor a keyword), clean, count withcollections.Counter, render withWordCloud.generate_from_frequencies(). - Defaults are not enough: on raw tweets the default
wordcloudsettings puthttps tandt coin the top four terms of all three of our samples (1,292 tweets, collected in 2026). - Add Twitter stopwords: the package's 192-word
STOPWORDSset has nohttps,co,amp,rtorvia; add them, strip @mentions and emoji, and drop reposts. - Remove the query words: in the "AI agents" search,
ai,agentsandagentwere 7.5% of all kept words and would fill the center of the cloud. - Pair the cloud with numbers: a top-25 table or bar chart gives the ranking and counts a cloud hides; we publish both for every sample.
- Cost: our 1,292-tweet study used 75 requests and about $0.19 of reads ($0.15 per 1,000 tweets; the official X API lists $0.005 per post read).
This guide is about one picture: a word cloud built from real tweets, either one account's recent posts or everything matching a search, made with Python code you run yourself. It is the visual cousin of our tweet sentiment analysis guide, which scores how posts feel; a word cloud only shows which words come up, and our pandas guide for Twitter data is the place for tables and time series once you want more than a picture.
Older tutorials on this topic lean on tools that no longer work the way they did: twint, the scraper many of them used, was archived by its owner on March 30, 2023 (the GitHub repo is read-only), and free tweepy access to the X API ended with the 2023 pricing changes. The plotting half of those tutorials is still right. The wordcloud package by Andreas Mueller is maintained, MIT licensed and at version 1.9.6 on PyPI, so this page keeps that part and replaces the data half with two REST endpoints.
To check what the advice is worth on real posts, we pulled 1,292 tweets (75 requests, collected in 2026) from two organization timelines, @NASA and @github, and from a search for "AI agents", then measured each cleaning step and rendered the clouds. Every number below comes from that study.
In all 3 samples (1,292 tweets, collected in 2026), the default wordcloud settings put https t and t co in the top four terms. Cleaning kept 48.6% to 57.0% of raw tokens.
What a Twitter word cloud shows, and when a bar chart is better
A word cloud draws each word with a font size proportional to how often it appears. It is good at one thing: giving a reader the gist of a body of text in a glance. It is a poor tool for anything that needs a precise comparison, because readers judge area badly, long words look bigger than short ones at the same count, and the layout is random, so position carries no meaning.
That trade-off shows up in our data. In the "AI agents" search the top 25 terms covered only 13.6% of the kept words, and 46.6% of the 5,716 distinct terms appeared exactly once. The cloud is a fair summary of the head of that distribution; the long tail is invisible. The two timelines are more concentrated (18.9% for @NASA, 21.6% for @github), because a brand repeats its own product names.
Use a word cloud when the goal is a quick visual for a slide, a report cover, a newsletter, or a first look at an unfamiliar account or hashtag. Use a bar chart or table when someone will make a decision from the numbers, compare two periods, or compare two accounts. Our habit, which we follow on this page, is to publish both: the cloud for the eye, the top-25 table for the facts.
If you want to compare how posts feel rather than which words they use, a cloud is the wrong tool entirely; see the emotion analysis guide or the sentiment guide linked above.

Step 1: get the tweets (account timeline or keyword search)
There are two natural inputs for a Twitter word cloud. An account's own posts, which tell you what a brand, a newsroom or a public figure talks about. A keyword or hashtag search, which tells you what everyone says about a topic. Both are plain HTTPS GET calls with an X-API-Key header; no X account and no OAuth app are needed for reads.
Account timeline. GET /twitter/user/last_tweets with userName=NASA returns the latest posts of that account, newest first. The docs (docs.twitterapi.io/api-reference/endpoint/get_user_last_tweets) state that each page returns up to 20 tweets; the tweets sit in data.tweets, and has_next_page plus next_cursor (top level) give you the next page. Replies are left out unless you pass includeReplies=true, which is what you usually want for a cloud of what the account says itself.
Keyword search. GET /twitter/tweet/advanced_search takes query and queryType (Latest or Top) and returns tweets at the top level with the same cursor fields. The query uses X's search operators, so "AI agents" lang:en -filter:retweets gives English posts containing the phrase, without reposts. Our search sample returned 500 tweets in 25 pages.
Drop reposts from timelines. A timeline includes the account's reposts, and their text belongs to someone else. In our sample 189 of the 415 @NASA tweets and 102 of the 377 @github tweets were reposts (marked by a retweeted_tweet object and text starting with RT @). Keeping them would put other accounts' words, and their truncated text, into the brand's cloud.
How many tweets? A cloud stabilizes faster than you might think. A few hundred posts give a recognizable shape for a single account; for a busy keyword, 500 to 1,000 posts is a sensible start. Each 20-tweet page is one request, so 1,000 tweets is about 50 requests.
import os, requests
BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_API_KEY"]}
# one page of an account's latest posts (up to 20)
r = requests.get(f"{BASE}/twitter/user/last_tweets",
params={"userName": "NASA", "cursor": ""}, headers=HEADERS, timeout=30)
body = r.json()
tweets = body["data"]["tweets"]
print(len(tweets), body["has_next_page"], body["next_cursor"][:12])
# one page of a keyword search
r = requests.get(f"{BASE}/twitter/tweet/advanced_search",
params={"query": '"AI agents" lang:en -filter:retweets', "queryType": "Latest", "cursor": ""},
headers=HEADERS, timeout=30)
body = r.json()
print(len(body["tweets"]), body["has_next_page"])
Step 2: clean the text (where default settings go wrong)
Tweet text is noisier than prose. Almost every post carries a shortened https://t.co/... link, many carry @mentions and emoji, and the text arrives with HTML entities such as &. The wordcloud package has a built-in stopword list and its own tokenizer, so it is tempting to pass the raw text straight to WordCloud().generate(). We tried exactly that on each sample, using WordCloud().process_text() with every setting at its default, and listed the top terms it would draw:
The pattern is the same everywhere: https t and t co are pieces of every t.co link. They show up as two-word phrases because the package's collocations option is on by default (the docs: "Whether to include collocations (bigrams) of two words"), and its 192-word STOPWORDS set, which we inspected in version 1.9.6, has no entry for https, co, amp, rt or via. In the @NASA sample the handle Space_Station also ranked third, because the default tokenizer keeps the text after the @ sign.
The cleaning recipe we used, in order: decode HTML entities with html.unescape; replace URLs (https?://\S+); remove @mentions (@\w+); remove emoji; lowercase; keep tokens that start with a letter; fold possessive 's; then drop stopwords. The stopword set is the package's STOPWORDS plus 16 Twitter extras (amp, rt, via, https, co, contraction stubs like don and ll), 10 filler words that survive the default list (will, one, now, new, just, us and similar), and time-zone and month tokens (utc, et, pm, aug, oct), which event-heavy accounts repeat in nearly every post.
Roughly half of every post is dropped, and the stopword step does almost all of the cutting. URLs are a small share of tokens but a large share of posts: 97.8% of @NASA posts and 87.3% of @github posts carried a link, so one stray fragment per post is enough to top the cloud. Emoji are account-specific: 80.4% of @github posts had at least one, against 20.8% for @NASA.
Hashtags are a judgment call. We keep the word and drop the #, so #GitHubUniverse counts as githubuniverse. If you want hashtags only, our hashtag analytics guide reads them from entities.hashtags instead of the text.

Step 3: count the words and keep the numbers
Once each post is a list of clean tokens, counting is one line: collections.Counter. Do the counting yourself rather than letting WordCloud.generate() do it. You get a table you can print, sort, save to CSV and check, and the cloud then becomes a rendering of numbers you already trust. generate_from_frequencies() takes exactly that dictionary.
Remove your own query words for search clouds. A search for "AI agents" returns posts that all contain those words, so they dominate the count without telling you anything new. In our sample ai (871), agents (729) and agent (272) together were 7.5% of all kept words, several times the next term. The search cloud on this page leaves them out; the code at the bottom does the same automatically for any query.
Plural folding. The package's normalize_plurals option (on by default) merges a word with its trailing-s plural, but the docs note it is ignored when you use generate_from_frequencies. That is why agent and agents, or model and models, are separate rows in our counts. If you want them merged, fold them in your own cleaning step or use a lemmatizer from NLTK or spaCy.
Here are the top 25 terms for each sample after cleaning, with counts. This is the table every cloud on this page is drawn from:
The account clouds read like a content plan: @NASA posts are about live coverage, crews, missions and the Moon, and @github posts are about Copilot, the app and the CLI. The search cloud is flatter and more abstract (building, work, people, real), which is typical for a broad topic discussed by many different authors.

Step 4: render the cloud with the wordcloud package
Install with pip install wordcloud (or conda install -c conda-forge wordcloud); the README lists numpy, pillow and matplotlib as dependencies, and PyPI lists Python 3.9 or newer for version 1.9.6. Then build a WordCloud object and feed it the counts.
Size. The defaults are width=400 and height=200 pixels, which is small for anything you will publish. We used 1200 by 630 for a social card, or three 520 by 640 panels for the comparison figure above.
Background and palette. The default background_color is black and the default colormap is viridis. On a white background, pale colors from a sequential colormap can be nearly invisible for small words; we hit this in our first render and switched to a color_func that picks from four dark shades. Pass random_state to get the same layout on every run.
Word count. max_words defaults to 200. For tweets, 80 to 100 words is usually enough; past that, the extra words are tiny and add clutter.
Shape. Pass a mask (a numpy array from an image) to fill a shape such as a logo silhouette; white areas of the mask stay empty. Use an image you have the right to use.
Command line. The package also ships wordcloud_cli (wordcloud_cli --text mytext.txt --imagefile wordcloud.png), handy for a quick look at a text file you already cleaned.
from wordcloud import WordCloud
# counts is a collections.Counter built in step 3
wc = WordCloud(
width=1200, height=630, # defaults are 400 x 200
background_color="white", # default is black
max_words=100, # default is 200
prefer_horizontal=0.9,
random_state=7, # same layout every run
).generate_from_frequencies(dict(counts.most_common(100)))
wc.to_file("tweet_word_cloud.png")
Account cloud vs search cloud: what each one tells you
An account cloud is a portrait of what one voice chooses to say. It is concentrated: the account's own name and product names sit at the top (github and copilot were the two largest @github terms by a wide margin), and the rest is the vocabulary of its campaigns. It is useful for competitor research, for checking whether your own posts match your positioning, and for a before/after view of a launch.
A search cloud is a portrait of a conversation. It is flatter (13.6% top-25 coverage in our sample versus about 20% for the timelines) and more varied (5,716 distinct terms from 500 posts). It is useful for spotting the angles people take on a topic, but it is also sensitive to a few prolific authors and to spam, so filter with operators such as lang:en, -filter:retweets and min_faves:5 before you draw conclusions.
For a hashtag cloud, search for the hashtag (#yourtag) and count the other words in those posts, or count the co-occurring hashtags from entities.hashtags. Either way, remove the hashtag you searched for, for the same reason you remove query words.
Compare periods with separate clouds and the same settings. Advanced search accepts since_time:<unix> and until_time:<unix>, so you can fetch the week before and the week after an event and draw two clouds with identical stopwords and random_state. Then compare the two tables, not the two pictures.
Word cloud generators vs code: which to use
Online word cloud generators that take pasted text are fine for a one-off: copy a handful of posts, paste, download. They stop being practical when you need hundreds of posts, a repeatable result, your own stopword list, or the counts behind the picture. Several of the twitter word cloud generator projects on GitHub that come up in search depend on twint or on credentials for the old free X API tiers, so check the last commit and the data source before you rely on one.
The script below is a generator in about 100 lines of Python: give it a username or a search query and it writes a PNG and prints the top-25 table. Wrap it in a small Streamlit app (see our Streamlit guide) if non-developers on your team need a text box and a button.
What it costs to make a word cloud from tweets
Reads on twitterapi.io are billed per tweet returned: 15 credits per tweet, which is $0.15 per 1,000 tweets, with a minimum of 15 credits ($0.00015) per request, so a full 20-tweet page costs $0.003. There is no X developer account to apply for, and new accounts that pass the automatic check get free starter credits (no card, one per person or network, expiring after 31 days); see pricing for the current amount.
Our whole study, 1,292 tweets in 75 requests, cost about $0.19. The same 1,292 post reads at the official X API pay-per-usage rate of $0.005 per post read (docs.x.com pricing page) would be about $6.46, roughly 33 times more per 1,000 tweets. The official API also caps pay-per-usage plans at 3 million post reads per monthly billing cycle, which a word cloud project will never approach.
Rate limits matter more than price for a cloud. Before your first payment the limit is 0.2 requests per second, so 50 pages take a little over 4 minutes with a fixed 5-second pause; after the first payment it is 20 requests per second. The script's PAUSE constant is the only thing to change.
How we collected this
Question. What does a word cloud built from real tweets show once URLs, mentions, stopwords and emoji are cleaned out, and what does skipping the cleaning do to the picture?
Accounts and query. The latest posts of two organization accounts, @NASA (415 tweets) and @github (377 tweets), via /twitter/user/last_tweets with default settings (no replies), 25 pages each; and the latest 500 posts matching "AI agents" lang:en -filter:retweets via /twitter/tweet/advanced_search with queryType=Latest, 25 pages.
Window and size. Collected in 2026. Each timeline sample covers that account's latest few hundred posts; the search sample covers a few hours of matching posts at collection time. 1,292 tweets returned, 1,001 used after dropping reposts, 75 requests, about $0.19 of reads.
Method. Tokens were counted with the cleaning recipe in Step 2 (wordcloud 1.9.6 STOPWORDS plus Twitter extras, filler and schedule words). The "default settings" table comes from WordCloud().process_text() on the uncleaned text of the same posts. Clouds were rendered with generate_from_frequencies() from the top 80 terms of each sample. The analysis and chart scripts are in the study folder.
What the sample cannot show. Three samples from one collection run are not a census: a different week, account or query will give different words, and a search sample from a few hours over-represents whoever posted a lot in those hours. The cleaning shares depend on how a given account writes (link-heavy, emoji-heavy). We did not measure how readers perceive the clouds.
Privacy. Aggregates only. The two timelines belong to organizations. Search results come from private individuals: their raw text is not published or stored with this page, no handle or post is quoted, and @handles are removed from every cloud and table.
"""tweet_word_cloud.py - build a word cloud (plus a top-terms table) from an X (Twitter)
account's posts or from a keyword search, using twitterapi.io and the wordcloud package.
pip install requests wordcloud matplotlib
export TWITTERAPI_IO_API_KEY=... # from your twitterapi.io dashboard
python tweet_word_cloud.py --user NASA --pages 10
python tweet_word_cloud.py --search '"AI agents" lang:en -filter:retweets' --pages 10
"""
import argparse
import html
import os
import re
import time
from collections import Counter
import requests
from wordcloud import STOPWORDS, WordCloud
BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_API_KEY"]}
PAUSE = 5.0 # 0.2 requests/s before your first payment; 0.05 is fine once paid (20 requests/s)
URL_RE = re.compile(r"https?://\S+")
MENTION_RE = re.compile(r"@\w+")
EMOJI_RE = re.compile("[\U0001F000-\U0001FAFF\u2600-\u27BF\u2B00-\u2BFF\uFE0F\u200D]+")
WORD_RE = re.compile(r"[a-z][a-z0-9']+")
# Twitter noise that the wordcloud STOPWORDS set does not cover, plus filler words
EXTRA = {"amp", "rt", "via", "https", "http", "co", "t", "gt", "lt", "s", "don", "ll", "re", "ve",
"im", "dont", "us", "will", "one", "now", "new", "just", "get", "also", "still", "every"}
def fetch_user(user_name, pages):
"""Latest posts of one account, newest first (up to 20 per page)."""
tweets, cursor = [], ""
for _ in range(pages):
r = requests.get(f"{BASE}/twitter/user/last_tweets",
params={"userName": user_name, "cursor": cursor}, headers=HEADERS, timeout=30)
r.raise_for_status()
body = r.json()
tweets += (body.get("data") or {}).get("tweets", [])
if not body.get("has_next_page") or not body.get("next_cursor"):
break
cursor = body["next_cursor"]
time.sleep(PAUSE)
return tweets
def fetch_search(query, pages):
"""Latest posts matching an advanced-search query (up to 20 per page)."""
tweets, cursor = [], ""
for _ in range(pages):
r = requests.get(f"{BASE}/twitter/tweet/advanced_search",
params={"query": query, "queryType": "Latest", "cursor": cursor},
headers=HEADERS, timeout=30)
if r.status_code == 503: # temporary upstream throttle: wait and retry the same page
time.sleep(60)
continue
r.raise_for_status()
body = r.json()
tweets += body.get("tweets", [])
if not body.get("has_next_page") or not body.get("next_cursor"):
break
cursor = body["next_cursor"]
time.sleep(PAUSE)
return tweets
def clean(text, drop):
text = html.unescape(text).replace("\u2019", "'")
text = URL_RE.sub(" ", text)
text = MENTION_RE.sub(" ", text)
text = EMOJI_RE.sub(" ", text)
words = [w.strip("'") for w in WORD_RE.findall(text.lower())]
words = [w[:-2] if w.endswith("'s") else w for w in words]
return [w for w in words if w not in drop and len(w) >= 2 and not w.isdigit()]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--user")
ap.add_argument("--search")
ap.add_argument("--pages", type=int, default=10)
ap.add_argument("--out", default="wordcloud.png")
a = ap.parse_args()
tweets = fetch_user(a.user, a.pages) if a.user else fetch_search(a.search, a.pages)
seen, own = set(), []
for t in tweets: # dedupe and drop reposts: their text belongs to someone else
if t["id"] in seen or t.get("retweeted_tweet") or t["text"].startswith("RT @"):
continue
seen.add(t["id"])
own.append(t)
drop = set(STOPWORDS) | EXTRA
if a.search: # the query words would dwarf everything else
drop |= {w for w in WORD_RE.findall(a.search.lower()) if w not in ("lang", "filter", "retweets")}
counts = Counter()
for t in own:
counts.update(clean(t["text"], drop))
print(f"{len(own)} posts, {sum(counts.values())} kept words, {len(counts)} distinct terms")
for rank, (word, n) in enumerate(counts.most_common(25), 1):
print(f"{rank:>2}. {word:<20} {n}")
wc = WordCloud(width=1200, height=630, background_color="white", max_words=100,
random_state=7).generate_from_frequencies(dict(counts.most_common(100)))
wc.to_file(a.out)
print("saved", a.out)
if __name__ == "__main__":
main()
Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.
Questions readers ask
How do I make a word cloud from tweets?
Fetch the tweets (for one account, /twitter/user/last_tweets; for a keyword, /twitter/tweet/advanced_search), remove URLs, @mentions, emoji and stopwords, count the remaining words with collections.Counter, and pass the counts to WordCloud().generate_from_frequencies() from the Python wordcloud package. The full script on this page does all four steps and also prints a top-25 table.
Why does my Twitter word cloud show https and co?
Every tweet with a link contains a t.co URL, and the wordcloud package's built-in STOPWORDS list (192 words in version 1.9.6) does not include https, co, amp, rt or via. With collocations on by default, the fragments appear as the phrases 'https t' and 't co'. In our three samples they landed in the top four terms every time. Remove URLs with a regular expression before counting, and add those tokens to your stopwords.
Is there a free Twitter word cloud generator?
Paste-text web generators are free for small one-off clouds. For a cloud from hundreds of posts, the Python wordcloud package is free and MIT licensed; you pay only for the tweets you read. On twitterapi.io that is $0.15 per 1,000 tweets, and new accounts get free starter credits (no card, one per person or network, expiring after 31 days).
Can I make a word cloud from a hashtag?
Yes. Search for the hashtag with /twitter/tweet/advanced_search (for example query '#yourtag lang:en -filter:retweets', queryType Latest), then count the words in those posts, or count the co-occurring hashtags from entities.hashtags. Remove the hashtag you searched for, since every post contains it.
How many tweets do I need for a meaningful word cloud?
For one account, a few hundred of its own posts usually give a stable shape; our @NASA and @github clouds used 226 and 275 posts after dropping reposts. For a broad keyword, start with 500 to 1,000 posts, because the vocabulary is spread over many authors: our 500-post search had 5,716 distinct terms.
Should I remove the search keyword from the word cloud?
Yes. Every post in a keyword search contains the keyword, so it dominates the count without adding information. In our 'AI agents' sample the words ai, agents and agent were 7.5% of all kept words. Drop them, and drop the hashtag for hashtag searches.
Do I need an X developer account or API key from X?
Not for reads through twitterapi.io: you need a twitterapi.io API key sent in the X-API-Key header, and no X account. If you use the official X API instead, you need an X developer account, and post reads are billed at $0.005 each on pay-per-usage.
Is a word cloud good for analysis?
It is good for a quick visual summary and poor for precise comparison: readers judge area badly, longer words look bigger, and the layout is random. Publish the counts next to it as a table or bar chart, and use sentiment, emotion or topic models when you need more than word frequency.
Continue
- wordcloud docs: WordCloud class (defaults, collocations, normalize_plurals, generate_from_frequencies)
- amueller/word_cloud on GitHub (MIT license, install, wordcloud_cli)
- wordcloud on PyPI (version 1.9.6, Python 3.9 or newer)
- twitterapi.io docs: Get user last tweets
- twitterapi.io docs: Advanced search
- X API pricing (official per-resource rates)
- X (Twitter) API overview and endpoints
- Analyze Twitter data with pandas
- Twitter sentiment analysis in Python
- Hashtag analytics with the Twitter API
- Build a Twitter dashboard with Streamlit
- Topic modeling on tweets
- twitterapi.io pricing per 1,000 tweets
- 01Twitter (X) Fake News Detection: Datasets, Features and Code
- 02Twitter (X) Topic Modeling in Python: BERTopic vs LDA on Real Tweets
- 03Twitter (X) Hate Speech Detection in Python: Models, Thresholds and a Real Reply Study
- 04Spark Streaming Twitter (X) Data in 2026: PySpark Structured Streaming Without TwitterUtils
- 05Twitter (X) API to Neo4j: model, import and query a real follower and mention graph
- 06Sam Altman on Twitter — A Tracking Guide for AI Developers & Researchers
- 07How to Embed a Video on Twitter (X): In a Post or on Your Website
- 08How to Get a Claude API Key: Console Steps, Billing, First Call and Live X (Twitter) Data
Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.
Stop reading. Start building.
Starter credits cover real testing on real data. Google sign-in, no card, no application queue.
Get an API keyAlready building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.