Can We Use Python to Plot in Tableau?
So, you know your way around both Python and Tableau and wonder if you can bring these two powerhouses together. Combining Python’s data wrangling muscle with Tableau’s visualization brilliance sounds like the perfect analytics setup. The good news is, you absolutely can - just maybe not in the way you first imagine. This article walks you through the two primary methods for making Python and Tableau work together, so you can decide which approach is right for your project.
Not Directly, but Absolutely: Understanding the Partnership
You can't open Tableau and start writing Python code to render a bar chart like you would with a library such as Matplotlib or Seaborn. Tableau is a specific, self-contained tool for visualization with its own drag-and-drop interface. The magic happens when you use Python to empower your Tableau dashboards, either by preparing the data beforehand or by running live calculations in the background.
Think of it as a partnership where each tool plays to its strengths:
- Python does the heavy lifting: complex data cleaning, advanced transformations, statistical modeling, or running machine learning predictions.
- Tableau handles the final presentation: creating stunning, interactive visuals and dashboards that people can easily explore.
There are two main ways to create this partnership:
- Preprocessing Data: Use Python to prepare a clean, analysis-ready dataset, then load that file into Tableau. This is the simplest and most common workflow.
- Using TabPy (Tableau Python Server): Connect Tableau directly to a Python service to execute scripts in real-time right inside your Tableau workbooks. This is the more advanced approach for dynamic analysis.
Let’s break down how to use both methods with practical examples.
Method 1: The Preprocessing Workflow (Simple & Powerful)
For many everyday analytics tasks, the most straightforward approach is to let Python handle all your data manipulation first. You can run complex operations that would be difficult or impossible in Tableau alone, such as building a customer segmentation model or generating a sales forecast, and then pass the final, clean dataset over to Tableau for visualization.
This method doesn't require any special server setup - just your regular Python environment (like a Jupyter Notebook) and Tableau Desktop.
Free PDF · the crash course
AI Agents for Marketing Crash Course
Learn how to deploy AI marketing agents across your go-to-market — the best tools, prompts, and workflows to turn your data into autonomous execution without writing code.
Step-by-Step Example: Customer Segmentation
Let's imagine you have a CSV file with customer sales data, and you want to group your customers into 'High Value', 'Medium Value', and 'Low Value' segments based on their total spending. This kind of segmentation is a perfect job for Python's scikit-learn library.
Step 1: Get & Understand Your Data
First, assume you have a file named sales_data.csv with columns like CustomerID, OrderID, and SaleAmount.
Step 2: Process Using Python & Pandas
You'll use the pandas library to load the data, aggregate it to find total spending per customer, and then use a simple function to assign segments. For a more advanced approach, you could use a clustering algorithm like K-Means.
Here’s what the Python script could look like:
import pandas as pd
# Load the raw sales data
df = pd.read_csv('sales_data.csv')
# Calculate total sales for each customer
customer_value = df.groupby('CustomerID')['SaleAmount'].sum().reset_index()
# Define a function to segment customers based on spending
def segment_customer(total_sales):
if total_sales > 5000:
return 'High Value'
elif 2000 <= total_sales <= 5000:
return 'Medium Value'
else:
return 'Low Value'
# Apply the function to create a new 'Segment' column
customer_value['Segment'] = customer_value['SaleAmount'].apply(segment_customer)
# Check the first few rows of our new DataFrame
print(customer_value.head())When you run this script, Python performs the aggregation and adds a brand new Segment column to your data.
Step 3: Save the Processed Data
Next, save your newly enhanced DataFrame to a fresh CSV file that Tableau will use.
# Save the new DataFrame to a CSV file for Tableau
customer_value.to_csv('customer_segments.csv', index=False)Step 4: Connect Tableau to Your New Data
Now, it's Tableau's turn. Open Tableau and connect to the new file, customer_segments.csv. You’ll immediately see your fields, including the CustomerID, SaleAmount, and the new Segment field calculated by Python.
Step 5: Plot in Tableau
With your data loaded, creating a visual is just a matter of dragging and dropping. For example, you can:
- Drag
Segmentto the Columns shelf. - Drag
CustomerIDto the Rows shelf and change its measure to Count (Distinct).
In seconds, you'll have a bar chart showing the number of customers in each segment. The heavy computation was handled by Python, while the intuitive and fast visualization was done in Tableau.
When to Use This Method
The preprocessing workflow is perfect when:
- You have complex data cleaning or transformation needs.
- You want to incorporate a machine learning model's output (e.g., predictions, clusters).
- Your analysis doesn't need to change in real-time based on a filter in a dashboard.
Method 2: Real-Time Power with TabPy
What if you want Python’s power to run dynamically within your Tableau dashboard? That’s where TabPy comes in. TabPy is an analytics extension from Tableau that allows you to execute Python code in real-time from inside Tableau calculated fields.
When a user interacts with a dashboard - say, by adjusting a filter - Tableau sends the data and your script to the TabPy server, which runs the Python code and sends the results straight back to your visualization.
Step-by-Step Guide to Using TabPy
Setting up TabPy requires a few more steps, but it unlocks incredible new capabilities for interactive analysis.
Step 1: Install & Run TabPy
First, you need to install TabPy, which is a standard Python package. Open your terminal or command prompt and run:
pip install tabpyOnce installed, you can start the server by running this simple command:
tabpyYou’ll see a message confirming that the server is running on port 9004.
Step 2: Connect Tableau to the TabPy Server
In Tableau Desktop, you need to tell it where to find your running TabPy instance:
- Navigate to Help > Settings and Performance > Manage Analytics Extension Connection.
- In the dialog box, select TabPy.
- Enter the server as
localhostand the port as9004. - Click Test Connection to make sure everything is working. You should see a success message.
Step 3: Create a Python Calculated Field
Now for the fun part. You can create a calculated field in Tableau that uses Python. These calculations use special SCRIPT_* functions (SCRIPT_REAL, SCRIPT_INT, SCRIPT_STR) to send code and data to TabPy.
Let's use an example of sentiment analysis on customer feedback text. This is something Tableau can't do natively, but it's simple with Python's TextBlob library. First, make sure you have it installed (pip install textblob).
Assuming you have a field in your data called [Review Text], create a new calculated field named Sentiment Score with the following formula:
SCRIPT_REAL("
from textblob import TextBlob
results = []
for review in _arg1:
sentiment = TextBlob(review).sentiment.polarity
results.append(sentiment)
return results
",
[Review Text]
)Let's break down this syntax:
SCRIPT_REALtells Tableau we expect Python to return a list of numbers (real numbers, or floats).- The code inside the quotes is the actual Python script that will be executed by TabPy.
_arg1is a special placeholder that represents the data being passed from Tableau. In this case, it's the[Review Text]field.- The
AVG([Review Text])is purely a placeholder to help with Tableau aggregations in the view. What matters is that[Review Text]is being provided to the script. We are using AVG since it only passes one mark per Review Text entry. The individual text values will be what populates_arg1list passed to TabPy.
Free PDF · the crash course
AI Agents for Marketing Crash Course
Learn how to deploy AI marketing agents across your go-to-market — the best tools, prompts, and workflows to turn your data into autonomous execution without writing code.
Step 4: Visualize the Python Output
You can now use your Sentiment Score calculated field just like any other measure in Tableau. Drag it to your view to analyze sentiment across different product categories, time periods, or customer segments. The calculation runs live, so if you filter the data, Tableau automatically re-runs the Python script on the new subset of data!
When to Use TabPy
TabPy is your best choice when:
- You need dynamic or "what-if" analysis right in a dashboard.
- You want to run predictions from a trained model in real-time based on user inputs.
- You're using Python libraries for tasks that Tableau cannot do, like natural language processing, complex simulations, or specialized statistical functions.
Choosing the Right Tool for the Job
The Python and Tableau integration isn't about choosing one over the other - it's about creating a modern data stack where each tool handles its part of the workflow perfectly.
- Use Python for:
- Use Tableau for:
Final Thoughts
So yes, you can definitely use Python to enhance your plotting capabilities in Tableau. You accomplish this by leveraging Python for the upfront data science and transformation tasks, then feeding the results into Tableau for best-in-class interactive visualization. Whether you choose the simple preprocessing method or the dynamic TabPy integration, combining these tools opens up a new world of analytical possibilities.
A central challenge in data analytics is the friction between complex preparation and final visualization. We built Graphed to remove this friction entirely, especially for marketing and sales teams. Instead of writing scripts in Python or wrangling clunky BI tools, you can connect your data sources (like Google Analytics, Shopify, and Salesforce) and build incredible real-time dashboards just by asking questions in plain English. It's like having a data analyst baked into your workflow, turning hours of work into a 30-second conversation.
Related Articles
How to Create Facebook Ads API for Claude Code
Create a Meta Marketing API access token that never expires, using a system user, so Claude Code can pull Facebook ad reports and manage campaigns.
ClickHouse vs Postgres: When to Switch to Columnar
Comparing ClickHouse vs PostgreSQL means matching storage architecture to workload. Row storage wins for transactions. Columnar wins for scan-heavy analytics.
Google Ads for Orthodontists: Get More Booked Consults
Most orthodontic Google Ads campaigns waste money on low-intent searches. The problem is structure, not the platform.