Twitter (X) Network Analysis with Python and networkx: A Real #reInvent Graph

- Nodes are accounts, edges are actions. A retweet, quote, reply or mention becomes a directed edge
actor -> target, weighted by how often it happened. - Real graph, collected in 2026: 799 #reInvent posts produced 622 nodes and 430 edges; retweets were 52% of edge events.
- Sparse and fragmented: 251 weakly connected components; the largest holds 40.5% of accounts, and 65.4% of accounts have in-degree 0.
- Communities follow language: Louvain found 261 communities (modularity 0.8343); the largest is a 99% Japanese-language cluster with no organization hub.
- Query precision decides the graph: the bare word
reInventreturned 1,500 posts, only 9.3% about the conference; the hashtag / exact phrase query was 91.1% on topic. - Cost: 118 requests and 2,359 tweets for $0.35 at $0.15 per 1,000 tweets; the same reads on the official X API rate card ($0.005 per post read) come to $11.79.
The top results for "twitter network analysis" are mostly papers from the follow-graph era and tutorials built on the free v1.1 API and rtweet / Tweepy collection code that no longer runs as written. The concepts in them still hold (DataCamp's lesson defines a retweet network as a directed graph from the retweeting user to the original poster; Pew's 2014 study mapped six conversation structures with NodeXL). What they lack is a pipeline you can run today and numbers from a graph built today.
This guide is that pipeline, end to end in Python: pull posts for a topic, turn them into a weighted directed graph with networkx, compute components, degree, PageRank, betweenness and communities, and export a GEXF file for Gephi. Every number on the page comes from one real run on AWS re:Invent chatter: 799 posts over about 50 hours, collected in 2026. We also ran a deliberately sloppy query on the same event, because the clearest lesson of the study is that the query shapes the graph more than any algorithm does.
65.4%
What a Twitter (X) interaction network is: nodes, edges and weights
A network is a set of nodes joined by edges. On X there are two very different networks people mean by "Twitter network analysis". The follow graph (who follows whom) is large and slow to change; Myers and colleagues analyzed a 2012 snapshot with about 175 million active users and roughly twenty billion edges (WWW 2014). The interaction graph is built from what accounts do in a window of time: who retweets, quotes, replies to and mentions whom about a topic. This page builds the second kind, because it answers topic questions (who drives the conversation, which groups exist, who bridges them) from a few thousand posts.
Direction. An edge points from the account that acted to the account it acted on. If account A retweets B, the edge is A -> B. A high in-degree means many accounts amplified or addressed you; a high out-degree means you amplified or addressed many others.
Weight. If A retweets B three times and mentions B once, keep one edge A -> B with weight=4 and per-type counts (retweet=3, mention=1). Weighted degree and weighted PageRank then reflect intensity, and the per-type counts let you filter later (a pure retweet network, a reply network).
Edge types and what they mean. A retweet is amplification without comment. A quote is amplification with comment (often disagreement). A reply is conversation. A mention is addressing or tagging. They mix differently by topic: in our #reInvent graph the edge events were:
Two rules keep the counts honest. First, skip the mention list of a retweet: those mentions were written by the original author, so counting them would credit the retweeter with edges they never made. Second, drop the reply target from a reply's mention list, or each reply is counted twice.
Step 1: collect the posts for one topic
Network analysis needs the interactions themselves, so collect posts that carry them: retweets (with the original author attached), quotes, replies and mentions. /twitter/tweet/advanced_search takes the same query operators as X search, returns 20 posts per page newest first with queryType=Latest, and pages with has_next_page and next_cursor. Add include:nativeretweets so retweets come back with a retweeted_tweet object; in our probe without it, none of the 20 posts returned was a retweet, and the retweet layer is the largest layer of the graph in our run.
Each post object carries everything the graph needs: author.userName, retweeted_tweet, quoted_tweet, inReplyToUsername, and entities.user_mentions, plus createdAt, lang and the counts (likeCount, retweetCount, replyCount, quoteCount, viewCount) for node or edge attributes. No X account or developer app is needed for reads: an API key in the X-API-Key header is enough.
Budget the window, not just the topic. A conference hashtag in the days before the event produced about 16 posts an hour in our run; 40 pages (800 posts) reached back about 50 hours. A busy news topic can fill the same 40 pages in minutes. Decide the time window you want to describe, then size the page count, and report both.
import time
import requests
API_KEY = "YOUR_API_KEY"
BASE = "https://api.twitterapi.io"
QUERY = '(#reInvent OR "re:Invent" OR #AWSreInvent) include:nativeretweets'
def collect(query, max_pages=40):
"""Page through advanced_search (Latest), 20 posts per page, newest first."""
tweets, cursor = [], ""
for _ in range(max_pages):
params = {"query": query, "queryType": "Latest"}
if cursor:
params["cursor"] = cursor
r = requests.get(f"{BASE}/twitter/tweet/advanced_search",
headers={"X-API-Key": API_KEY}, params=params, timeout=30)
r.raise_for_status()
body = r.json()
tweets.extend(body.get("tweets", []))
if not body.get("has_next_page"):
break
cursor = body.get("next_cursor", "")
time.sleep(0.2)
return tweets
tweets = collect(QUERY)
print(len(tweets), "posts")Step 2: build the weighted graph with networkx
Use a networkx.DiGraph with lowercased handles as node keys (X handles are case-insensitive, and the same account appears as AWSCloud in one mention and awscloud in another). Add every author as a node even if they have no edges, so isolates are counted: in our run, 195 of 622 nodes were isolates, posts about the topic that touched nobody else.
Mention and reply targets that never posted in your window still become nodes. They are often the important ones: 121 of our 622 nodes never posted a matching post themselves, yet several (for example @AWS) ranked high on PageRank because others kept pointing at them. If you need profile fields for those nodes, look them up afterward with /twitter/user/info (18 credits per profile).
networkx 3.2.1 ran this study on Python 3.9. Note the version gap if you install fresh: the latest networkx on PyPI is 3.7, which requires Python 3.12 or newer, so an older interpreter quietly gets an older networkx. The code here uses only functions that exist in both. PageRank in networkx 3.x imports scipy, so install it alongside.
import networkx as nx
def build_graph(tweets):
"""Edge a -> b: a retweeted, quoted, replied to or mentioned b."""
G = nx.DiGraph()
def add(a, b, kind):
a, b = a.lower(), b.lower()
if not a or not b or a == b:
return
if G.has_edge(a, b):
G[a][b]["weight"] += 1
G[a][b][kind] = G[a][b].get(kind, 0) + 1
else:
G.add_edge(a, b, weight=1, **{kind: 1})
for t in tweets:
author = t["author"]["userName"]
G.add_node(author.lower())
rt = t.get("retweeted_tweet")
if rt and rt.get("author"):
add(author, rt["author"]["userName"], "retweet")
continue # mentions inside a retweet belong to the original author
q = t.get("quoted_tweet")
if q and q.get("author"):
add(author, q["author"]["userName"], "quote")
reply_to = (t.get("inReplyToUsername") or "").lower()
if reply_to:
add(author, reply_to, "reply")
for m in (t.get("entities") or {}).get("user_mentions") or []:
name = (m.get("screen_name") or "").lower()
if name and name != reply_to:
add(author, name, "mention")
return GStep 3: measure size, components and degree
Start with the shape before the rankings. These numbers tell you whether there is one conversation or many unrelated ones, and whether the rankings below mean anything.
Sparse is normal. A density of 0.001113 means about one in a thousand possible edges exists, and reciprocity of 0.0372 means fewer than 4% of edges are returned. Topic graphs are mostly one-way amplification: many accounts point at few, and the few rarely point back.
Degree is heavy-tailed. 65.4% of accounts have weighted in-degree 0 and 23.8% have exactly 1. Only 5 accounts reach 10 or more, and the top five absorb 24.5% of all edge weight. The maximum in-degree was 49 and the median was 0. Plot the distribution before quoting any averages: a mean of a distribution like this describes almost nobody.

Step 4: centrality: who gets amplified and who bridges
Three centrality measures answer three different questions, and they disagree in useful ways. Weighted in-degree counts how often an account was retweeted, quoted, replied to or mentioned. PageRank weights those edges by the importance of whoever sent them, so a mention from a well-connected account counts more. Betweenness counts how often an account lies on shortest paths between others: high betweenness marks a bridge between clusters, even with modest in-degree. On a graph of a few hundred nodes exact betweenness is fast; on larger graphs pass k (we used k=500, seed=42) to sample source nodes and keep it reproducible.
Top 10 by betweenness in our graph (organization and public accounts named; individual accounts shown only by follower bucket):
The official @awscloud account led all three measures (in-degree 49, PageRank 0.0433, betweenness 0.0855). Below it the lists split. PageRank put @AWSDevelopers, @jeffbarr, @McKinsey and @AWS in its top 10. Betweenness instead surfaced @EvanKirstel and @QuinnyPig, accounts with lower in-degree that connect otherwise separate English-language groups, and an unofficial party-listing account, @reInventParties, that links attendee clusters. Six of the top 10 bridges were individual accounts, all under 100k followers: in a topic graph, the bridges are often practitioners, not brands.
Do not rank by followers. Follower count is a property of the account; centrality is a property of this conversation. The second-highest in-degree in our graph belonged to an account with 1k to 10k followers, ahead of accounts with more than 100k.
from networkx.algorithms import community as nxcom
G = build_graph(tweets)
print(G.number_of_nodes(), "nodes", G.number_of_edges(), "edges")
wcc = sorted(nx.weakly_connected_components(G), key=len, reverse=True)
print("components:", len(wcc), "largest:", len(wcc[0]))
in_deg = dict(G.in_degree(weight="weight"))
pagerank = nx.pagerank(G, weight="weight") # needs scipy
U = G.to_undirected()
betweenness = nx.betweenness_centrality(U, k=min(500, len(U)), seed=42)
# Communities on an undirected, weight-summed projection
UW = nx.Graph()
for a, b, d in G.edges(data=True):
w = d["weight"] + (UW[a][b]["weight"] if UW.has_edge(a, b) else 0)
UW.add_edge(a, b, weight=w)
UW.add_nodes_from(G.nodes)
louvain = sorted(nxcom.louvain_communities(UW, weight="weight", seed=42), key=len, reverse=True)
print("communities:", len(louvain), "modularity:",
round(nxcom.modularity(UW, louvain, weight="weight"), 4))
print("largest five:", [len(c) for c in louvain[:5]])Step 5: community detection (Louvain, greedy modularity) and Gephi export
Community detection groups accounts that interact with each other more than with the rest. networkx ships louvain_communities(G, weight='weight', resolution=1, threshold=1e-07, max_level=None, seed=None) and greedy_modularity_communities. Both work on undirected graphs, so project the DiGraph first and sum the weights of A -> B and B -> A. Fix seed for Louvain, because its result depends on node order.
The high community count is mostly the 232 components of one or two accounts: every isolate is its own community. Read the large ones. Louvain produced 9 communities of 10 or more accounts, and labeling them by the lang of their members' posts showed the structure at once:
Two of the six largest communities are Japanese-language clusters with no organization account at their center: AWS user-group members and community builders talking to each other ahead of the event. Japanese posts were 334 of 799 in the sample. The English side splits around the official account, around @jeffbarr, around @AWSDevelopers and around @QuinnyPig's commentary. Greedy modularity merges some of these (its largest community has 74 accounts) at a slightly lower modularity of 0.8271 versus 0.8343, so report which method you used and its seed.
Label communities with data, not guesses. Language, the hashtags members use, and their named hubs are cheap labels you already have in the post JSON. Avoid inferring sensitive traits of private members from community membership.
Gephi is the free, open-source (GPL) desktop tool many researchers use for network layout; a web version, Gephi Lite, also exists. nx.write_gexf(G, path) writes GEXF (default version='1.2draft'), and Gephi imports node and edge attributes as data-table columns. Store in-degree, PageRank and the Louvain community id on each node before exporting, then in Gephi run a ForceAtlas2 layout, size nodes by PageRank and color them by community.
Keep private handles out of shared images. A labeled network drawing of a topic graph is mostly private individuals. For anything you publish, label only organization or public accounts, or replace labels with community ids. We did not publish a node-link drawing for that reason; the GEXF stays on the analyst's machine.
Large graphs. networkx is comfortable up to tens of thousands of edges on a laptop. For millions, export an edge list (nx.write_weighted_edgelist) and move to a graph library written in C or Rust; the edge-building logic above stays the same.
# Gephi reads GEXF. Edge attributes (weight, retweet, reply, ...) become columns.
H = G.copy()
for node in H.nodes:
H.nodes[node]["in_degree"] = in_deg.get(node, 0)
H.nodes[node]["pagerank"] = round(pagerank.get(node, 0.0), 6)
for i, members in enumerate(louvain):
for node in members:
H.nodes[node]["community"] = i
nx.write_gexf(H, "reinvent.gexf")
The query decides the graph: a bare word vs a hashtag
Before the main run we searched the bare word reInvent (with #reInvent and #reInvent2026 as alternatives). It returned 1,500 posts in about 41 hours, far more than the hashtag query. Only 9.3% of them mentioned the conference, the hashtag, AWS or Amazon. The rest used "reinvent" as an ordinary verb (reinventing yourself, a brand, a recipe), and a single individual account unrelated to the event drew the largest share of edges.
In the broad graph the top in-degree was 266, for an unrelated individual account, while @awscloud had 6. Every centrality ranking from that graph would have described the wrong conversation, with no error message to warn you. Two habits prevent it: use hashtags, exact phrases ("re:Invent") and handles rather than common words, and measure the on-topic share of the first few pages before you build the graph.

Cost of collecting network data: per-tweet pricing vs the official X API
Network studies read many posts and keep all of them, so the read price matters. Tweet endpoints such as /twitter/tweet/advanced_search cost 15 credits per tweet returned, $0.15 per 1,000 tweets, with a minimum of 15 credits per request (an empty search costs $0.00015; a full 20-post page costs $0.003). This whole study, 118 requests including three probes and the discarded broad query, returned 2,359 tweets for 35,385 credits, $0.35.
The official X API pay-per-usage rate card (docs.x.com/x-api/getting-started/pricing) lists $0.005 per post read and $0.010 per user read, capped at 3 million post reads per monthly billing cycle. The same 2,359 post reads at $0.005 come to $11.79. Per 1,000 posts that is $5 on X's rate card against $0.15 here, about 33 times.
If you also need follower edges (the follow graph), followers and followings lists cost 1 to 3 credits per user returned, and profiles 18 credits per user ($0.18 per 1,000). New accounts that pass the automatic bot check get free starter credits (no card, one per person or network, expiring after 31 days); purchased credits never expire. Before the first payment the rate limit is 0.2 requests per second, 20 once paid.
How we collected this
Question. What does the interaction network around one public tech-event topic look like: size, components, degree, communities, and which organization or public accounts are central?
Query and endpoint. /twitter/tweet/advanced_search with queryType=Latest, following next_cursor. Main graph: (#reInvent OR "re:Invent" OR #AWSreInvent) include:nativeretweets, 40 pages. Comparison: (reInvent OR #reInvent OR #reInvent2026) include:nativeretweets, 75 pages.
Window and sample. The latest matching posts at collection time, collected in 2026: 799 posts over about 50 hours for the main graph and 1,500 posts over about 41 hours for the comparison. 118 requests in total, 2,359 tweets returned. Analysis with networkx 3.2.1; Louvain seed 42; betweenness sampled with k=500, seed 42.
What the sample cannot show. It covers two days before the event, not the event itself, so the official account's dominance may shrink once sessions start. Search returns what X search indexes for a query; deleted, protected and filtered posts are absent. The graph contains only interactions inside the topic query, not follows, likes or private messages. Community labels come from post language and named accounts, not from any judgment about members.
Privacy. Public posts only. Raw search pages were kept out of the repository because the authors are mainly private individuals; the study folder holds aggregates and a de-identified edge list (rank numbers, follower buckets, edge-type counts; no handles, ids, URLs or text). Only organization and public accounts are named.
import time
import networkx as nx
import requests
from networkx.algorithms import community as nxcom
API_KEY = "YOUR_API_KEY"
BASE = "https://api.twitterapi.io"
QUERY = '(#reInvent OR "re:Invent" OR #AWSreInvent) include:nativeretweets'
def collect(query, max_pages=40):
"""Page through advanced_search (Latest), 20 posts per page, newest first."""
tweets, cursor = [], ""
for _ in range(max_pages):
params = {"query": query, "queryType": "Latest"}
if cursor:
params["cursor"] = cursor
r = requests.get(f"{BASE}/twitter/tweet/advanced_search",
headers={"X-API-Key": API_KEY}, params=params, timeout=30)
r.raise_for_status()
body = r.json()
tweets.extend(body.get("tweets", []))
if not body.get("has_next_page"):
break
cursor = body.get("next_cursor", "")
time.sleep(0.2)
return tweets
tweets = collect(QUERY)
print(len(tweets), "posts")
def build_graph(tweets):
"""Edge a -> b: a retweeted, quoted, replied to or mentioned b."""
G = nx.DiGraph()
def add(a, b, kind):
a, b = a.lower(), b.lower()
if not a or not b or a == b:
return
if G.has_edge(a, b):
G[a][b]["weight"] += 1
G[a][b][kind] = G[a][b].get(kind, 0) + 1
else:
G.add_edge(a, b, weight=1, **{kind: 1})
for t in tweets:
author = t["author"]["userName"]
G.add_node(author.lower())
rt = t.get("retweeted_tweet")
if rt and rt.get("author"):
add(author, rt["author"]["userName"], "retweet")
continue # mentions inside a retweet belong to the original author
q = t.get("quoted_tweet")
if q and q.get("author"):
add(author, q["author"]["userName"], "quote")
reply_to = (t.get("inReplyToUsername") or "").lower()
if reply_to:
add(author, reply_to, "reply")
for m in (t.get("entities") or {}).get("user_mentions") or []:
name = (m.get("screen_name") or "").lower()
if name and name != reply_to:
add(author, name, "mention")
return G
G = build_graph(tweets)
print(G.number_of_nodes(), "nodes", G.number_of_edges(), "edges")
wcc = sorted(nx.weakly_connected_components(G), key=len, reverse=True)
print("components:", len(wcc), "largest:", len(wcc[0]))
in_deg = dict(G.in_degree(weight="weight"))
pagerank = nx.pagerank(G, weight="weight") # needs scipy
U = G.to_undirected()
betweenness = nx.betweenness_centrality(U, k=min(500, len(U)), seed=42)
# Communities on an undirected, weight-summed projection
UW = nx.Graph()
for a, b, d in G.edges(data=True):
w = d["weight"] + (UW[a][b]["weight"] if UW.has_edge(a, b) else 0)
UW.add_edge(a, b, weight=w)
UW.add_nodes_from(G.nodes)
louvain = sorted(nxcom.louvain_communities(UW, weight="weight", seed=42), key=len, reverse=True)
print("communities:", len(louvain), "modularity:",
round(nxcom.modularity(UW, louvain, weight="weight"), 4))
print("largest five:", [len(c) for c in louvain[:5]])
# Gephi reads GEXF. Edge attributes (weight, retweet, reply, ...) become columns.
H = G.copy()
for node in H.nodes:
H.nodes[node]["in_degree"] = in_deg.get(node, 0)
H.nodes[node]["pagerank"] = round(pagerank.get(node, 0.0), 6)
for i, members in enumerate(louvain):
for node in members:
H.nodes[node]["community"] = i
nx.write_gexf(H, "reinvent.gexf")Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.
Questions readers ask
What is Twitter network analysis?
It is the study of relationships between X accounts as a graph. Accounts are nodes; follows, retweets, quotes, replies or mentions are edges. Researchers use it to find influential accounts (centrality), groups that talk among themselves (communities) and accounts that connect groups (bridges).
Which Python library should I use for Twitter network analysis?
networkx is the common starting point: it covers directed weighted graphs, PageRank, betweenness, Louvain and greedy modularity communities, and GEXF export for Gephi. For graphs with millions of edges, export an edge list and use a compiled graph library; the edge-building code stays the same.
Should I build a follower network or a retweet network?
For a topic question (who drives this conversation, which groups exist), build an interaction network from retweets, quotes, replies and mentions in a time window: a few thousand posts are enough. A follower network describes long-term audience structure and needs far more data, because large accounts have millions of followers.
How many tweets do I need for a meaningful network?
Enough to give the largest component a few hundred nodes. Our 799-post sample produced a 252-node largest component and 9 communities of 10 or more accounts. Check the on-topic share first: a common-word query can return many posts and a meaningless graph.
Can I still use Tweepy or rtweet for network analysis?
Both libraries call the official X API, which now bills per resource on its pay-per-usage rate card ($0.005 per post read per docs.x.com). Older tutorials that relied on free v1.1 search no longer run as written. Any source of post JSON with author, retweet, quote, reply and mention fields works with the graph code on this page.
How do I open a Twitter network in Gephi?
Write the networkx graph with nx.write_gexf(G, 'graph.gexf') and open the file in Gephi. Store attributes such as PageRank and community id on the nodes first; Gephi shows them as columns you can size and color by.
Is it ethical to publish Twitter network graphs?
Publish aggregates and name only organization or public accounts. Topic graphs are mainly private individuals, so labeled node-link drawings can expose them; replace private labels with community ids or counts, and keep raw data out of public repositories.
Continue
- networkx: louvain_communities reference
- networkx: write_gexf reference
- networkx on PyPI (version and Python requirement)
- Gephi: open-source network visualization
- X API pricing (pay-per-usage rate card)
- TwitterAPI.io docs: advanced_search and user endpoints
- X API guide: endpoints, pricing and access options
- Twitter (X) data collection API developer guide
- Twitter (X) API for academic research
- Export a Twitter (X) dataset for research
- Export a following list to build a follow graph
- Tweet metadata fields reference (retweeted_tweet, entities, lang)
- TwitterAPI.io pricing per tweet and per profile
- TwitterAPI.io API documentation
- 01How to Translate Tweets on Twitter (X): Auto-Translate, the Gear Icon and Language Settings
- 02How to Turn Off Autoplay on Twitter (X): App, Web and Auto-Advance
- 03Twitter (X) and the EU Digital Services Act (DSA): What the Commission Found, and What It Means for X Data
- 04Twitter (X) and Firebase: store posts in Firestore with a scheduled Cloud Function
- 05Analyze Twitter (X) Data with pandas: A Worked Example on 1,800 Real Posts
- 06Twitter (X) Analysis API — A Developer's Guide
- 07Twitter (X) Sentiment Analysis in Python: Pull Posts, Score Them, Compare Two Scorers
- 08Twitter (X) Competitor Analysis — A Developer's API Guide
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.