How to implement Sentiment Analysis in Tableau using R

Interactive sentiment analysis with Tableau using R
Interactive sentiment analysis with Tableau using R

In my previous post I highlighted Tableau’s text mining capabilities, resulting in fancy visuals such as word clouds:

Today I’d like to follow up on this and show how to implement sentiment analysis in Tableau using Tableau’s R integration. Some of the many uses of social media analytics is sentiment analysis where we evaluate whether posts on a specific issue are positive, neutral, or negative (polarity), and which emotion in predominant.

What do customers like or dislike about your products? How do people perceive your brand compared to last year?

In order to answer such questions in Tableau, we need to install an R package that is capable of performing the sentiment analysis. In the following example we use an extended version of the sentiment package, which was initiated by Timothy P. Jurka.

The sentiment package requires the tm and Rstem packages, so make sure that they are installed properly. Execute these commands in your R console to install sentiment from GitHub (see alternative way to install at the end of this blog post):


install.packages("devtools")
library(devtools)
install_github("aloth/sentiment/sentiment")

The sentiment package offers two functions, which can be easily called from calculated fields in Tableau:

Screenshot 2016-01-31 15.25.24 crop

The function get_polarity returns „positive“, „neutral“, or „negative“:


SCRIPT_STR('
library(sentiment)
get_polarity(.arg1, algorithm = "bayes")
'
, ATTR([Tweet Text]))

The function get_emotion returns „anger“, „disgust“, „fear“, „joy“, „sadness“, „surprise“, or „NA“:


SCRIPT_STR('
library(sentiment)
get_emotion(.arg1, algorithm = "bayes")
'
, ATTR([Tweet Text]))

The sentiment package follows a lexicon based approach and comes with two files emotions_english.csv.gz (source and structure) and subjectivity_english.csv.gz (source and structure). Both files contain word lists in English and are stored in the R package library under /sentiment/data directory.

If text is incorrectly classified, you could easily fix this issue by extending these two files. If your aim is to analyze text other than English, you need to create word lists for the target language. Kindly share them in the comments!

Feel free to download the Packaged Workbook (twbx) here.

Update 11 Aug 2016: If you are having trouble with install_github, try to install directly form this website:


install.packages("Rcpp")
install.packages("https://alexloth.com/utils/sentiment/current/sentiment.zip",repos=NULL)

How to perform Text Mining at the Speed of Thought directly in Tableau

Interactive real-time text mining with Tableau Desktop 9.2
Interactive real-time text mining with Tableau Desktop

Tableau is an incredibly versatile tool, commonly known for its ability to create stunning visualizations. But did you know that with Tableau, you can also perform real-time, interactive text mining? Let’s delve into how we can harness this function to gain rapid insights from our textual data.

Previously, during text mining tasks, you might have found yourself reaching for a scripting language like R, Python, or Ruby, only to feed the results back into Tableau for visualization. This approach has Tableau serving merely as a communications tool to represent insights.

However, wouldn’t it be more convenient and efficient to perform text mining and further analysis directly in Tableau?

While Tableau has some relatively basic text processing functions that can be used for calculated fields, these often fall short when it comes to performing tasks like sentiment analysis, where text needs to be split into tokens. Even Tableau’s beloved R integration does not lend a hand in these scenarios.

The Power of Postgres for Text Mining in Tableau

Faced with these challenges, I decided to harness the power of Postgres‘ built-in string functions for text mining tasks. These functions perform much faster than most scripting languages. For example, I used the function regexp_split_to_table for word count, which takes a piece of text (like a blog post), splits it by a pattern, and returns the tokens as rows:

select
guid
, regexp_split_to_table(lower(post_content), '\s+') as word
, count(1) as word_count
from
alexblog_posts
group by
guid, word

Incorporating Custom SQL into Tableau Visualization

I joined this code snippet as a Custom SQL Query to my Tableau data source, which is connected to the database that is powering my blog:

Join with Custom SQL Query in Tableau applying the Postgres function regexp_split_to_table
Join with Custom SQL Query in Tableau applying the Postgres function regexp_split_to_table

And here we go, I was able to create an interactive word count visualization right in Tableau:

This example can be easily enhanced with data from Google Analytics, or adapted to analyze user comments, survey results, or social media feeds. The possibilities for Custom SQL in Tableau are vast and versatile. Do you have some more fancy ideas for real-time text mining with Tableau? Leave me a comment!

Update (TC Pro Tip): Identifying Twitter Hashtags in Tableau

A simple calculated field in Tableau can help identify words within tweets as hashtags or user references, eliminating the need for another regular expression via a Custom SQL Query:

CASE LEFT([Word], 1)
WHEN "#" THEN "Hash Tag"
WHEN "@" THEN "User Reference"
ELSE "Regular Content"
END

Looking for an example? Feel free to check out the Tweets featuring #tableau Dashboard on Tableau Public and download the Packaged Workbook (twbx):

Tableau dashboard that shows tweets featuring the hashtag #tableau (presented at Tableau Conference)
Tableau dashboard that shows tweets featuring the hashtag #tableau (presented at Tableau Conference)

Any more feedback, ideas, or questions? I hope this post provides you with valuable insights into how to master text mining in Tableau, and I look forward to hearing about your experiences and creative applications. You can find more tutorials like this in my new book Visual Analytics with Tableau (Amazon).

Transparency: This blog contains affiliate links. If you click on them, you will be redirected to the merchant. If you decide to make a purchase, we will receive a small commission. The price does not change for you. Affiliate links have no influence on our writing.

KPMG Global Automotive Executive Survey 2016

KPMG Global Automotive Executive Survey 2016: click to open interactive story
KPMG Global Automotive Executive Survey 2016: click to open interactive story

In the recent months, 800 automotive executives from 38 countries gave their insights to KPMG. You can discover the key highlights of the KPMG Global Automotive Executive Survey in this eye-catching interactive Tableau story.

This is a fabulous example how you can use stories to present a narrative to an audience. Just as dashboards provide spatial arrangements of analysis that work together, stories present sequential arrangements of analysis that create a narrative flow for your audience.

5 Vorteile von Data Science

Deutschherrnbrücke mit Skyline von Frankfurt am Main
Nicht nur Banken handeln ihre Daten als Gold des 21. Jahrhunderts

Keine Frage, die Digitalisierung prägt unseren Alltag und stellt auch an Banken immer neue Anforderungen. Daten werden als das neue Gold gehandelt. Und genau darin liegt die große Chance der Banken: Finanzinstitute hatten schon immer enorme Mengen an Daten, oft aus vielen verschiedenen Quellen. Aber wie wird das volle Potenzial dieser Daten genutzt und wie werden Erkenntnisse aus diesen gewonnen? Hier kommt Data Science ins Spiel.

Wie gewinnen Sie Erkenntnisse aus Ihren Daten?

Data Science verwendet Methoden aus der Mathematik, Statistik und Informationstechnologie. Data Scientists verfügen darüber hinaus über ausgeprägte Kommunikationsfähigkeiten auf sämtlichen Ebenen eines Unternehmens und bereiten Ergebnisse für das Management der einzelnen Fachabteilungen genauso verständlich auf wie für den CEO. Banken können dazu neben Kontoinformationen auch Kundentransaktionen, Kundenkommunikation, Kanalnutzung, Kundenverhalten und Social-Media-Aktivitäten. Vieles davon wird idealerweise nahezu in Echtzeit verarbeitet und ausgewertet.

Der Daten-Leverage-Effekt:

Da der Bankensektor weiterhin mit knappen Margen und und schwindendem Gewinn zu kämpfen hat, ist es für Finanzinstitute äußerst wichtig einen Hebel anzulegen, um Kosten zu reduzieren, Kunden zu binden und neue Einnahmequellen zu erschließen. Einen solchen Daten-Leverage-Effekt erzielen Sie mit ihren Daten – sofern Sie auf Data Science und damit einhergehend auf eine erweiterte Analyse setzen.

Betrachten Sie diese fünf Vorteile:

  1. Bessere Erkenntnisse: Gewinnen Sie eine neue Sicht auf Ihre treuesten und profitabelsten Kunden und verstehen Sie deren Bedürfnisse bereits vor dem Kundengespräch. Datenanalyse kann helfen, den Überblick zu behalten und Vorschläge für entsprechende Kommunikationskanäle zu liefern.

  2. Kundenbindung: Sorgen Sie für zufriedenere Kunden und finden Wege treue Kunden zu belohnen. Zudem lassen sich Kunden identifizieren, die ggf. eine Kündigung erwägen. Führen Sie dazu die Metriken „Loyalität“ und „Churn“ ein, um hierfür ein Messinstrument zu haben.

  3. Kostengünstiges Marketing: Entwickeln Sie effektives Marketing und Kampagnen, die an die richtige Person zur richtigen Zeit ausgerichtet sind. Dabei hilft Ihnen eine Cluster-Analyse, um Kundensegmente zu identifizieren.

  4. Minimieren von Risiken: Beschleunigen und verbessern Sie Ihr Risiko- und Fraud-Management durch Mustererkennung und Maschinenlernen.

  5. Handeln Sie: Behalten Sie Ihr Dashboard mit den wesentlichen Kennzahlen im Auge und ergreifen Maßnahmen, deren Auswirkung Sie zeitnah beobachten können. Nutzen Sie die Daten und Vorhersagen als Kernelement für Ihre Storyboards mit denen Sie das Top-Management überzeugen.

Nutzen Sie bereits die richtigen Werkzeugen zur Datenanalyse und Datenvisualisierung in Ihrem Unternehmen? Falls nicht, wäre es nun an der Zeit über den Einsatz von Data Science nachzudenken.

Beitrag zuerst veröffentlicht am 19.06.2015 im Capgemini IT-Trends-Blog.

IMF Global Data Explorer

How about some visual takeaways from the IMF’s World Economic Outlook? Recently I prepared two nifty data visualizations with Tableau that I like to share with you.

These visualizations allow you to explore plenty of economical data, including IMF staff estimates until 2020. Don’t forget to choose „Units“ after switching „Subject“ on the right-side bar. A detailed description on each subject is displayed below.

Tableau