Twitter (X) Emotion Analysis in Python: Multi-Label Emotions on Real Posts, Model vs Lexicon

By TwitterAPI.io Team•15 min read
Diagram of a Twitter (X) emotion analysis pipeline. Step 1: pull posts with /twitter/tweet/advanced_search, query "spotify wrapped" lang:en -filter:retweets, 1,100 posts. The posts go to three scorers: a multi-label model with 11 labels (cardiffnlp twitter-roberta, sigmoid, keep scores at or above 0.5), a single-label model with 7 classes (j-hartmann distilroberta, Ekman six plus neutral, argmax) and a word lexicon with 8 emotions (NRC Emotion Lexicon via NRCLex). Result box: joy on 60.3% of posts under the multi-label model, neutral top for 43.1% under the single-label model, no emotion word in 46.7% under the lexicon.
The pipeline this page builds: one search call pages the posts, three scorers label the same text, and the result box shows how differently they read it. Numbers come from the study below, collected in 2026.
TL;DR
  • Emotion is not sentiment. Sentiment gives one polarity per post; emotion analysis gives a set of labels (joy, anger, fear, sadness, love, optimism...). A post can be joy + love + optimism at once: 54.9% of our posts got two or more labels.
  • Pull: /twitter/tweet/advanced_search with queryType=Latest, follow next_cursor while has_next_page is true. 1,120 posts in 56 requests cost $0.168 ($0.15 per 1,000 posts returned).
  • Score: cardiffnlp/twitter-roberta-base-emotion-multilabel-latest, a RoBERTa model trained on SemEval-2018 Task 1 E-c tweets; sigmoid scores, keep labels at or above 0.5. It ran at 33.7 posts per second on a laptop CPU.
  • The threshold is the headline: moving it from 0.5 to 0.3 raised the joy share from 60.3% to 69.5%; at 0.7 it fell to 52.1%. Report the threshold with every number.
  • Lexicons miss slang and misfire on topic words: the NRC lexicon found no emotion word in 46.7% of posts, and "top" (11.5% of posts) counts as trust and anticipation. Use it as a transparent baseline, not the answer.
  • Datasets: SemEval-2018 Task 1 E-c (11 emotions, 6,838 / 886 / 3,259 English tweets) and TweetEval emotion (4 labels). Neither model card on Hugging Face declares a license, and the NRC lexicon needs a license for commercial use.

This page is about emotion classes, not polarity. Twitter sentiment analysis asks one question per post (positive, neutral or negative?) and our sentiment guide covers that end to end. Twitter emotion analysis asks a different one: which emotions does the post carry, and how many at once? Joy, anger, fear, sadness, disgust, surprise, love, optimism, anticipation. A furious post and a frightened post are both "negative" to a sentiment scorer; to an emotion model they are different signals with different consequences for a brand, a newsroom or a research project.

We built the whole pipeline in Python and ran it on real data: 1,100 English posts about one live, emotionally loud topic (Spotify Wrapped), pulled through twitterapi.io and scored by three methods on a laptop. The page shows the code, the label sets and licenses of the models and datasets we checked on Hugging Face, and the part tutorials skip: how often the methods disagree, and how far one threshold setting moves the result.

If you only need the code, jump to the end of the page: it is one runnable script that searches, scores, writes a CSV and prints the emotion mix per hour.

Posts the NRC lexicon could not tag with any emotion, out of 1,100

46.7% vs 10.9% for a tweet-trained model. Spotify Wrapped posts collected in 2026; where both named a top emotion they agreed 55.2% of the time (kappa 0.32).

01 — Section

What Twitter emotion analysis is, how it differs from sentiment, and three ways to do it

Sentiment analysis maps a post to a single point on a negative-to-positive axis. Emotion analysis maps it to a set of categories drawn from a psychological model. The two common label sets are Ekman's six basic emotions (anger, disgust, fear, joy, sadness, surprise) and Plutchik's eight (the same six plus anticipation and trust). The SemEval-2018 Affect in Tweets task, a widely used tweet benchmark, used Plutchik's eight plus love, optimism and pessimism: 11 labels, any number of which may apply to one tweet.

That last point is the practical difference. A post can be joyful and loving and optimistic at once, or angry and disgusted at once. In our sample, 54.9% of posts carried two or more emotions above the 0.5 threshold, and the model averaged 1.65 labels per post. A single-label classifier has to throw that information away.

QuestionSentiment analysisEmotion analysis
Output per postOne label or scoreA set of labels with scores
Typical labelsnegative, neutral, positivejoy, anger, fear, sadness, love, optimism...
Common tweet modeltwitter-roberta-base-sentiment-latesttwitter-roberta-base-emotion-multilabel-latest
Benchmark dataTweetEval sentiment subsetSemEval-2018 Task 1 (E-c subtask)
AnswersIs the reaction good or bad?What kind of reaction is it?

Use sentiment when you need one number on a dashboard. Use emotion when the kind of reaction matters: fear spikes after a product incident, anger at a pricing change, surprise at a launch, sadness around a farewell announcement. Many teams run both on the same posts. There are three practical ways to detect the emotions themselves.

Tweet-trained transformer models. Fine-tuned RoBERTa models on Hugging Face are the usual default. We checked two model cards this session. cardiffnlp/twitter-roberta-base-emotion-multilabel-latest is a fine-tune of cardiffnlp/twitter-roberta-base-2022-154m on SemEval-2018 Task 1 subtask E-c; it outputs 11 labels (anger, anticipation, disgust, fear, joy, love, optimism, pessimism, sadness, surprise, trust) and reports micro F1 0.7169, macro F1 0.5464 and a Jaccard index of 0.5970 on the test split. j-hartmann/emotion-english-distilroberta-base is a single-label DistilRoBERTa model for Ekman's six emotions plus neutral, trained on a balanced mix of six datasets (Twitter, Reddit, student self-reports and TV dialogue) and reporting 66% evaluation accuracy.

Licenses. Neither model card declares a license in its metadata (the Hugging Face API returns no license field for either, checked this session). The multi-label model inherits SemEval-2018 data, whose Hugging Face card points to the CodaLab terms. If you plan commercial use, ask the authors first rather than assuming a permissive license.

Word lexicons. The NRC Emotion Lexicon (Mohammad and Turney, National Research Council Canada) lists 14,182 English words, each crowd-annotated for association with eight emotions and two sentiments; the Python package NRCLex (version 4.1.0 on PyPI, MIT license for the code) bundles a version of it with 6,468 entries. A lexicon is fast and explainable: you can point to the word that fired. Its weaknesses are context, negation, slang and topic words, which our data shows clearly below. The NRC page states the lexicon is free for non-commercial research and educational use, and commercial use requires a license from NRC.

Large language models. You can also prompt an LLM to return emotion labels as JSON. It handles sarcasm and context better than a lexicon, but costs per post, varies between runs, and needs its own validation set. If you go that way, our tweet summarizer guide shows the pattern for sending batches of posts to a model. We did not benchmark an LLM in this study.

02 — Section

Step 1: pull the posts with one search endpoint

Emotion analysis needs text, timestamps and a stable id per post. On twitterapi.io one endpoint covers it: /twitter/tweet/advanced_search with the same query operators as X search. We used "spotify wrapped" lang:en -filter:retweets with queryType=Latest, which returns up to 20 posts per page, newest first, plus has_next_page and next_cursor for the next page. Each post carries id, text, createdAt, lang, likeCount, isReply and an author object.

Two filters matter for emotion work. lang:en keeps the input in the model's language (both models here are English-only). -filter:retweets removes copies, which otherwise multiply one person's emotion across hundreds of rows. Our 56 requests returned 1,120 posts covering 286 minutes of conversation (about 3.8 posts a minute); 1,100 were unique after de-duplication by id, because our first probe page repeated the newest 20 posts.

Cost: 15 credits per post returned, so $0.15 per 1,000 posts; a full 20-post page is $0.003 and an empty page costs the 15-credit minimum ($0.00015). The whole study cost $0.168. The same 1,120 post reads on the official X API pay-per-usage rate card ($0.005 per post read, docs.x.com/x-api/getting-started/pricing) would be $5.60, about 33 times more. No X developer account is needed for reads on twitterapi.io; see pricing for plans and the free starter credits (no card, one per person or network, expiring after 31 days).

If you already pull posts into a DataFrame, the Twitter data in pandas guide covers flattening the JSON; the emotion columns from this page slot in next to it.

python
import os, requests

API = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_API_KEY"]}

posts, cursor = [], ""
for _ in range(50):                     # 50 pages = up to 1,000 posts = about $0.15
    r = requests.get(f"{API}/twitter/tweet/advanced_search", headers=HEADERS, timeout=30,
                     params={"query": '"spotify wrapped" lang:en -filter:retweets',
                             "queryType": "Latest", "cursor": cursor})
    r.raise_for_status()
    body = r.json()
    posts += body.get("tweets", [])
    if not body.get("has_next_page"):
        break
    cursor = body["next_cursor"]
print(len(posts), posts[0]["createdAt"], posts[0]["text"][:80])
03 — Section

Step 2: clean the text and run a tweet-trained emotion model

The cardiffnlp tweet models were trained on text where links became http and mentions became @user, so mask yours the same way before scoring. Do not strip emoji: they carry a large share of the emotional signal in short posts (our median post was 15 words long).

The multi-label model outputs one independent score per emotion. Ask the Hugging Face pipeline for all scores (top_k=None) with a sigmoid (function_to_apply="sigmoid"), then keep every label at or above your threshold. We used 0.5. A post with no label above the threshold is your "no clear emotion" bucket, because this label set has no neutral class: that was 10.9% of our posts.

Speed: forcing the pipeline onto the CPU of an Apple M5 Pro laptop (device="cpu", batch size 32), the multi-label model scored 33.7 posts per second and the smaller DistilRoBERTa model 65.7. The first run downloads about 500 MB of weights for the RoBERTa model and about 330 MB for the DistilRoBERTa one. A GPU or Apple's mps device is faster, but CPU is enough for thousands of posts an hour.

python
import re
from transformers import pipeline   # pip install torch transformers

def clean(text):
    text = re.sub(r"https?://\S+", "http", text)
    text = re.sub(r"@\w+", "@user", text)
    return re.sub(r"\s+", " ", text).strip()

clf = pipeline("text-classification",
               model="cardiffnlp/twitter-roberta-base-emotion-multilabel-latest",
               top_k=None, function_to_apply="sigmoid", truncation=True, device="cpu")

scores = clf([clean(p["text"]) for p in posts], batch_size=32)
for p, s in zip(posts, scores):
    p["emotions"] = [d["label"] for d in s if d["score"] >= 0.5]   # may be empty
print(posts[0]["emotions"])
04 — Section

What 1,100 Spotify Wrapped posts showed under three scorers

We scored every post three ways: the 11-label multi-label model at a 0.5 threshold, the 7-class single-label model (top class wins), and the NRC lexicon (counts of emotion words; the emotion with the highest count wins, and equal counts are a tie). The chart compares the share of posts each method links to each emotion.

EmotionMulti-label modelSingle-label model (top class)NRC lexicon (any word)
joy60.3%20.1%24.9%
sadness16.4%7.2%18.4%
disgust16.2%1.5%10.7%
anger14.3%6.2%13.2%
surprise1.2%16.2%12.2%
fear1.1%5.7%13.2%
no emotion10.9% (no label at 0.5)43.1% (neutral)46.7% (no word)

Joy dominates, as expected for a year-in-music recap. The multi-label model put joy on 60.3% of posts, optimism on 22.6%, anticipation on 20.7% and love on 11.8%. The frequent combinations were joy alone (21.3%), joy + optimism (8.6%), anticipation + joy (8.3%) and joy + love + optimism (8.2%).

There is a real negative minority. Sadness (16.4%), disgust (16.2%) and anger (14.3%) were all in the double digits, and anger + disgust together was the top negative combination at 7.3% of posts: complaints about the recap format, irritation at everyone posting theirs, and embarrassment about one's own listening.

The scorers disagree on what "no emotion" means. The single-label model called 43.1% of posts neutral, the multi-label model left 10.9% without a label, and the lexicon found no emotion word in 46.7%. Same posts, a fourfold spread, purely from method.

Horizontal bar chart comparing, for 1,100 Spotify Wrapped posts, the share of posts the multi-label model tags with each emotion against the share containing at least one NRC lexicon word for it. Joy 60.3% vs 24.9%; optimism 22.6% (no lexicon label); anticipation 20.7% vs 29.7%; sadness 16.4% vs 18.4%; disgust 16.2% vs 10.7%; anger 14.3% vs 13.2%; love 11.8% (no lexicon label); fear 1.1% vs 13.2%; surprise 1.2% vs 12.2%; trust 0.0% vs 30.6%.
Same posts, two readings. The lexicon over-reports trust, fear and surprise because ordinary topic words carry those tags; the model reports far more joy. Spotify Wrapped posts in English, collected in 2026.
05 — Section

Where the model and the lexicon disagree, and why

To measure agreement fairly we compared only the six emotions all three methods share (anger, disgust, fear, joy, sadness, surprise), and only on posts where both methods named one of them as the top emotion. Cohen's kappa corrects the raw agreement for chance; values between 0.2 and 0.4 are usually read as fair agreement.

PairPosts comparedShare of sampleTop emotion agreesKappa
Multi-label vs single-label model57752.5%51.1%0.322
Multi-label model vs NRC lexicon968.7%55.2%0.32
Single-label model vs NRC lexicon777.0%49.4%0.326

The bigger story is the "posts compared" column. The lexicon produced a single winning emotion from the shared six on only 8.7% of posts: 46.7% had no emotion word, 31.4% were ties between emotions, and many of the rest were won by trust or anticipation. On joy alone, the model and the lexicon both saw it in 17.8% of posts, the model alone in 42.5%, the lexicon alone in 7.1%.

Topic words fire the lexicon. The word that matched the lexicon in the largest number of posts was "top" (11.5% of posts, as in "my top artist"), tagged anticipation and trust. Second was "music" (7.5%), tagged both joy and sadness. Neither says anything about the writer's feelings in a post about a music recap. Before trusting a lexicon on a topic, list its top matched words and drop the ones that are part of the topic itself.

Three hand-checked examples (paraphrased, not quoted). One post said the writer did not need the recap to know they had played a huge amount of one singer's music, used an expletive as an intensifier and ended with a heart-eyes emoji. The multi-label model said joy + love, which is right; the lexicon's top emotion was anger, triggered by the expletive; the single-label model said sadness. A second post, in capitals, said the writer had asked their mother about her recap, followed by an exclamation with an expletive and crying-laughing emojis. A human reads amused surprise; the single-label model said surprise, while the multi-label model said disgust + sadness + anger and the lexicon tied anger and disgust. A third post angrily asked why it mattered whether an artist appeared in someone's recap and whether that made them less of a real fan. Both models said anger (the multi-label model added disgust); the lexicon said trust, because "real" and "show" are trust words.

The pattern across the three: the lexicon is wrong whenever word choice and intent diverge (expletives used affectionately, topic words), and each model has blind spots of its own. The multi-label model rarely uses surprise (1.2% of posts) because surprise is rare in its training labels, so amused shock tends to land on other labels. Build a small hand-labeled set from your own topic before you report any shares.

Two-panel chart. Left: share of posts left with no emotion: multi-label model 10.9% (no label at 0.5), single-label model 43.1% (neutral wins), NRC lexicon 46.7% (no emotion word). Right: top-emotion agreement on the six shared labels: multi-label vs single-label 51.1% (kappa 0.322, 577 posts); multi-label vs lexicon 55.2% (kappa 0.32, 96 posts); single-label vs lexicon 49.4% (kappa 0.326, 77 posts).
Coverage and agreement of three emotion scorers on the same 1,100 posts, collected in 2026. Agreement is fair at best, and the lexicon names a usable top emotion for few posts.
06 — Section

Step 3: pick a threshold, aggregate by hour, and report it honestly

With a multi-label model the threshold is a modeling decision, not a detail. We re-ran the same scores at three thresholds:

ThresholdPosts with no labelPosts with joyLabels per post
0.31.6%69.5%2.42
0.510.9%60.3%1.65
0.723.2%52.1%1.13

A 17-point swing in the joy share from one setting is larger than many of the differences people try to read from emotion dashboards. Fix the threshold before you look at results, state it next to every share, and if you can, tune it on a few hundred posts you labeled yourself.

For time series, count posts per hour and the share of posts carrying each emotion in that hour. Shares are comparable across hours with different volumes; raw counts mostly track volume. Our window was short, so the hourly shares moved little:

Hour (UTC)PostsJoyAngerSadness
18:0011567.0%16.5%16.5%
19:0026761.0%11.6%19.5%
20:0024359.7%14.0%13.6%
21:0022853.5%17.5%15.4%
22:0019259.9%14.6%15.6%
23:005574.5%9.1%20.0%

The first and last hours are partial (the window started and ended inside them), which is why they have fewer posts; treat their shares with care. For a real monitor, keep a rolling baseline per topic and alert on a sustained jump in an emotion's share, not on one hour. Store the full score vector per post rather than only the labels so you can change the threshold later without re-scoring.

07 — Section

Twitter emotion datasets for training and evaluation

If you want to fine-tune your own model or measure one on labeled data, two published tweet datasets cover the emotion task. The TweetEval card adds a condition for all of its subsets: use must comply with X's terms of service and developer terms.

DatasetLabelsEnglish size (train / dev / test)License (as stated by the source)
SemEval-2018 Task 1, E-c subtask11 emotions, multi-label, plus neutral option during annotation6,838 / 886 / 3,259Hugging Face card lists "unknown" and points to the CodaLab terms
TweetEval, emotion subsetanger, joy, optimism, sadness (single label)3,257 / 374 / 1,421Card states "Undefined" for the emotion subset

SemEval-2018 Task 1 (Mohammad, Bravo-Marquez, Salameh and Kiritchenko, SemEval 2018) also includes emotion intensity tasks and Arabic and Spanish data. Its annotation guide defines each label broadly, for example anger also includes annoyance and rage, and trust includes acceptance, liking and admiration. That breadth matters when you read the output: "anger" from a model trained on it covers mild irritation too.

To build a dataset from your own topic, export posts and label a few hundred by hand. The research dataset export guide covers exporting search results to CSV or Parquet with the fields you need for that, and the network analysis guide shows how to add who-replies-to-whom structure if you want to see how emotion spreads between accounts.

08 — Section

Mistakes that quietly ruin a Twitter emotion analysis

Treating a threshold as a fact. As shown above, joy moved from 52.1% to 69.5% across sensible settings. Always publish it.

Using a lexicon without checking its top words. A topic word that happens to be in the lexicon ("top", "music", "show", "real") will tilt the whole result. List the top matched words first.

Forcing one label per post. Over half of our posts carried two or more emotions. Taking only the top label hides joy + love + optimism clusters and anger + disgust clusters, which are the interesting ones.

Keeping retweets. One emotional post retweeted a thousand times becomes a thousand rows. Use -filter:retweets in the query, or de-duplicate on the retweeted post's id.

Scoring the wrong language. Both models here are English-only. Filter with lang:en, or use a multilingual model and validate it per language.

Reading individuals. Emotion labels on one person's posts are a weak and sensitive signal. Aggregate over many posts and accounts, and do not build profiles of private individuals.

Skipping validation. Published F1 scores are on the benchmark's tweets, not your topic. A model with micro F1 0.72 on SemEval can do much worse on sports slang or crypto jargon. Hand-label a sample of your own posts and measure.

09 — Section

How we collected this

Question. On one live, emotionally loaded topic, what emotion mix do an open tweet-trained multi-label model, a single-label Ekman model and the NRC word lexicon assign to the same posts, and how often do they agree?

Query. "spotify wrapped" lang:en -filter:retweets on /twitter/tweet/advanced_search with queryType=Latest, 56 requests (one probe page plus 55 pages), 1,120 posts returned, 1,100 unique English posts analyzed, covering a 286-minute window. Collected in 2026. Cost $0.168 at 15 credits per post returned.

Method. Links masked as http, handles as @user. Model 1: cardiffnlp/twitter-roberta-base-emotion-multilabel-latest, sigmoid scores, labels at or above 0.5. Model 2: j-hartmann/emotion-english-distilroberta-base, highest of seven classes. Lexicon: NRCLex 4.1.0 with its bundled NRC lexicon, lowercase word tokens without lemmatization, highest emotion count wins, equal counts recorded as ties. All three ran locally on CPU in a throwaway Python 3.12 virtual environment.

What the sample cannot show. One topic, one few-hour window, English only, Latest search order. Spotify Wrapped skews joyful; a product outage or a political story would give a different mix. Agreement numbers depend on the label mapping we chose (six shared labels). We hand-checked examples, not a labeled set, so the page reports agreement between methods, not accuracy.

Privacy. The authors are private individuals, so raw pages stayed on the analysis machine and were not published. The study files keep only aggregates and de-identified rows (scores, labels, hour, word count; no ids, text, handles or links). The examples above are paraphrased.

The analysis script, results and de-identified sample are in our repository under data/studies/twitter-emotion-analysis/.

python
"""twitter_emotions.py - pull recent X (Twitter) posts on a topic and tag each one with
multi-label emotions (joy, anger, fear, sadness, optimism, ...), then print the mix per hour.

    pip install requests torch transformers
    export TWITTERAPI_IO_API_KEY=...          # twitterapi.io dashboard
    python twitter_emotions.py '"spotify wrapped" lang:en -filter:retweets' 50

Cost: each page of up to 20 posts is $0.003 (15 credits per post returned);
50 pages is about 1,000 posts, roughly $0.15. The model runs locally; a CPU is enough.
"""
import csv
import os
import re
import sys
import time
from collections import Counter, defaultdict
from datetime import datetime

import requests
from transformers import pipeline

API = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_API_KEY"]}
MODEL = "cardiffnlp/twitter-roberta-base-emotion-multilabel-latest"
THRESHOLD = 0.5   # a label counts when its sigmoid score is at least this


def fetch(query, max_pages):
    """Yield posts from advanced_search, newest first, following next_cursor."""
    cursor, seen = "", set()
    for _ in range(max_pages):
        r = requests.get(f"{API}/twitter/tweet/advanced_search", headers=HEADERS,
                         params={"query": query, "queryType": "Latest", "cursor": cursor}, timeout=30)
        if r.status_code == 429:          # paced too fast for your plan: wait, then try again
            time.sleep(5)
            continue
        r.raise_for_status()
        body = r.json()
        for t in body.get("tweets", []):
            if t["id"] not in seen:
                seen.add(t["id"])
                yield t
        if not body.get("has_next_page"):
            break
        cursor = body.get("next_cursor", "")
        time.sleep(0.2)                   # fixed pacing, well under the paid rate limit


def clean(text):
    """The cardiffnlp models were trained with links and handles masked like this."""
    text = re.sub(r"https?://\S+", "http", text)
    text = re.sub(r"@\w+", "@user", text)
    return re.sub(r"\s+", " ", text).strip()


def main():
    query = sys.argv[1] if len(sys.argv) > 1 else '"spotify wrapped" lang:en -filter:retweets'
    pages = int(sys.argv[2]) if len(sys.argv) > 2 else 10
    posts = list(fetch(query, pages))
    print(f"fetched {len(posts)} posts")
    if not posts:
        return

    clf = pipeline("text-classification", model=MODEL, top_k=None,
                   function_to_apply="sigmoid", truncation=True)
    scores = clf([clean(t["text"]) for t in posts], batch_size=32)

    rows, per_hour, overall = [], defaultdict(Counter), Counter()
    for t, s in zip(posts, scores):
        on = sorted((d["label"] for d in s if d["score"] >= THRESHOLD),
                    key=lambda k: -next(d["score"] for d in s if d["label"] == k))
        hour = datetime.strptime(t["createdAt"], "%a %b %d %H:%M:%S %z %Y").strftime("%Y-%m-%d %H:00")
        per_hour[hour]["posts"] += 1
        for label in on:
            per_hour[hour][label] += 1
            overall[label] += 1
        rows.append({"id": t["id"], "createdAt": t["createdAt"], "likes": t.get("likeCount", 0),
                     "emotions": "|".join(on) or "none",
                     **{d["label"]: round(d["score"], 3) for d in s}})

    with open("emotions.csv", "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0]))
        w.writeheader()
        w.writerows(rows)

    n = len(posts)
    print("share of posts carrying each emotion:")
    for label, c in overall.most_common():
        print(f"  {label:<13}{100 * c / n:5.1f}%")
    print(f"  {'(none)':<13}{100 * sum(r['emotions'] == 'none' for r in rows) / n:5.1f}%")
    print("\nper hour (UTC): posts, joy %, anger %, sadness %")
    for hour in sorted(per_hour):
        c = per_hour[hour]
        p = c["posts"]
        print(f"  {hour}  {p:4d}  {100 * c['joy'] / p:5.1f}  {100 * c['anger'] / p:5.1f}  {100 * c['sadness'] / p:5.1f}")


if __name__ == "__main__":
    main()

Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.

10 — Questions

Questions readers ask

What is the difference between Twitter sentiment analysis and emotion analysis?

Sentiment analysis gives each post one polarity (negative, neutral, positive). Emotion analysis gives it a set of emotion labels such as joy, anger, fear, sadness, love or optimism, often several at once. In our 1,100-post sample, 54.9% of posts carried two or more emotions under a multi-label model. See our separate Twitter sentiment analysis guide for the polarity task.

Which Hugging Face model is good for emotion detection on tweets?

For tweets, cardiffnlp/twitter-roberta-base-emotion-multilabel-latest is trained on SemEval-2018 Task 1 E-c tweets and outputs 11 labels with independent scores (reported micro F1 0.7169 on the test split). j-hartmann/emotion-english-distilroberta-base is a faster single-label option with Ekman's six emotions plus neutral, trained on a mix of Twitter, Reddit and other text. Validate either on your own topic before relying on it.

Is there a Twitter emotion dataset I can use?

Yes. SemEval-2018 Task 1 E-c has 11 emotion labels on English tweets (6,838 train, 886 validation, 3,259 test on its Hugging Face card) and TweetEval's emotion subset has four labels (anger, joy, optimism, sadness). The TweetEval card names no license for the emotion subset and requires compliance with X's terms; the SemEval card points to the CodaLab terms.

Is NRCLex good enough for Twitter emotion analysis?

As a transparent baseline, yes; as the final answer, rarely. In our sample it found no emotion word in 46.7% of posts, produced ties in 31.4%, and flagged trust in 30.6% mainly through topic words. Note the NRC lexicon is free for non-commercial research and needs a license from NRC for commercial use.

What threshold should I use for a multi-label emotion model?

0.5 is a common default, but tune it on posts you labeled yourself. On our data the share of posts with joy was 69.5% at 0.3, 60.3% at 0.5 and 52.1% at 0.7. Whatever you pick, publish it with the results and store the raw scores so you can change it later.

How much does it cost to collect tweets for emotion analysis?

On twitterapi.io, $0.15 per 1,000 posts returned (15 credits each), with a 15-credit minimum per request. Our 1,120 posts cost $0.168. On the official X API pay-per-usage rate card, post reads are $0.005 each, so the same reads would be $5.60. Scoring with an open model on your own machine adds no per-post fee.

Can I run emotion analysis on tweets without a GPU?

Yes. On the CPU of an Apple M5 Pro laptop the 11-label RoBERTa model scored 33.7 posts per second and the DistilRoBERTa model 65.7 posts per second at batch size 32, so tens of thousands of posts an hour are within reach on CPU.

Do I need an X developer account to pull tweets for this?

Not on twitterapi.io: reads need only an API key in the X-API-Key header, no X account. The official X API requires a developer account and a saved payment card for its pay-per-usage plan.

11 — Further reading

Continue

Sources & further reading
More from this series

Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.

Build it

Stop reading. Start building.

Starter credits cover real testing on real data. Google sign-in, no card, no application queue.

Get an API key

Already building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.