Lecture 12 - Data Visualization
Roadmap
- Data Visualization
- Type of Visualization
- Why it is Important
- Effective Visualization
- Comparison
- Composition
- Distribution
- Relationship
- Explore data with
- Apache Zeppelin
- Tableau
- Lab Challenge (AWS Academy)
- Glue
- Athena
- Tableau
What is Data Visualization?
- What is visualization?
- The use of computer-supported, interactive, visual representations of data to amplify cognition
- What is Data Visualization?
- Process by which numerical data are converted into meaningful 1-D, 2-D and 3-D
- Intended to analyze complex data
- Support interactive exploration in the shortest time
- To communicate information clearly and efficiently to users via the statistical graphics, plots, information graphics, tables, and charts selected
- "A picture is worth a thousand words"
A spreadsheet with 10,000 rows is like reading a phone book; a chart of the same data is like looking at a map. Same information, but your brain "gets it" in seconds instead of hours.
Visualization & Visual Analysis Reference Model

- The pipeline from data to what the user sees:
- Raw Data → Data Mining → Abstract Data
- Abstract Data → filtering / Encoding and Layout → Visual Form
- Visual Form → Rendering → View (seen by the user)
- The user interacts with the View, which feeds back to Data Mining and Encoding and Layout (interactive loop)
- Encoding : Visual Design
- Technique : Layout Algorithm
Like cooking: raw ingredients (raw data) → prep & chop (data mining) → decide the plating design (encoding & layout) → actually serve it on the plate (rendering) → the diner tastes it and asks for changes (feedback loop).
Factors to Consider When Selecting Tools

- Business needs
- Fully understand the business needs to be able to determine which data analyses and visualizations are needed to help develop insights
- Data characteristics
- Understand the type and quality of the data, and how often it is updated and processed
- Access to data
- Consider the data pipeline and who needs access to analyze and visualize data
Business Needs
- Which analyses are needed to help develop insights?
- What insights can be pulled from the data?
- What visualization would illustrate the insights?
- Does the consumer need to generate a report or interact with a dashboard?

- Key Attributes of an Actionable Insight:
- Alignment
- Context
- Relevance
- Specificity
- Novelty
- Clarity
An "actionable insight" is like a good doctor's diagnosis: it must be about your problem (alignment, relevance), explained with your history (context), precise (specificity), tell you something you didn't already know (novelty), and be easy to understand (clarity).
Business Needs: Granularity of Insight
| Industry | Detailed Level | Aggregate Level |
|---|---|---|
| Finance | A finance manager wants information (such as revenue, costs, and profit margins) about their line of business. | A CFO wants similar metrics at an aggregate level across all lines of businesses. They want to be able to drill down to any line of business. |
| Marketing | A marketing manager wants to know about the number of leads, opportunities, and closed deals within an area (such as a postal code or city). | A CMO is interested in related metrics but at a broader level (such as a state or region). |
| Sales | A sales manager is focused on their sales pipeline and wants to know how long it takes to close an opportunity. They want to assess how many opportunities are needed to achieve quota targets. | A VP of sales wants similar information at an aggregate level. They want to be able to drill down to a sales representative or sales territory. |
- Detailed level = managers working on one area
- Aggregate level = executives (CFO, CMO, VP) who see the big picture but want to drill down when needed
Like Google Maps: the executive looks at the whole country (aggregate), the manager zooms in to their own street (detailed). "Drill down" = zooming in.
Business Needs: Visualizing Insights

- KPIs
- Show performance in a particular area or function
- Relationships
- Establish or prove whether a relationship exists between two or more variables
- Comparisons
- Show or examine how different variables change over time or provide a static snapshot of how different variables compare
- Distributions
- Show how your data is distributed over certain intervals (based on clustering or grouping of data)
- Compositions
- Highlight the various elements that make up your data — its composition
Key Types of Analyses Typically Needed
Descriptive Analysis
- Descriptive Analysis: Summarize and understand the basic characteristics of the data
- Visualizations:
- Histograms (distribution of values)
- Bar charts (categorical comparisons)
- Pie charts (proportions)
- Insight: Answers "What happened?" or "What is happening?"
- Visualizations:

Diagnostic Analysis
- Diagnostic Analysis: Identify reasons behind patterns or anomalies
- Visualizations:
- Scatter plots (correlation between variables)
- Heatmaps (relationships and intensity)
- Box plots (outliers and variability)
- Insight: Answers "Why did it happen?"
- Visualizations:

Trend Analysis
- Trend Analysis: Detect changes over time
- Visualizations:
- Line charts (time series trends)
- Area charts (cumulative trends)
- Insight: Answers "How is it changing?"
- Visualizations:

Predictive Analysis
- Predictive Analysis: Forecast future outcomes using historical data
- Visualizations:
- Regression plots
- Forecast charts with confidence intervals
- Insight: Answers "What is likely to happen?"
- Visualizations:

- The fitted regression line in the example:
- where = income (in $10,000) and = happiness score → each extra $10,000 of income predicts about more happiness points
Comparative Analysis
- Comparative Analysis: Compare across groups, categories, or time periods
- Visualizations:
- Grouped bar charts
- Multi-line charts
- Insight: Answers "How do these compare?"
- Visualizations:

Correlation & Relationship Analysis
- Correlation & Relationship Analysis: Find associations between variables
- Visualizations:
- Scatter plots
- Correlation matrices
- Insight: Answers "What variables move together?"
- Visualizations:

Distribution & Variability Analysis
- Distribution & Variability Analysis: Understand spread and concentration of data
- Visualizations:
- Histograms
- Violin plots
- Insight: Answers "How is the data spread?"
- Visualizations:

Geospatial Analysis
- Geospatial Analysis (location involved): Analyze patterns across geographic regions
- Visualizations:
- Choropleth maps
- Bubble maps
- Insight: Answers "Where is it happening?"
- Visualizations:

Think of the analysis types as questions a detective asks:
- Descriptive = "What happened?" (the crime scene report)
- Diagnostic = "Why?" (the motive)
- Trend = "How is it changing?" (is crime rising?)
- Predictive = "What's next?" (where will they strike next?)
- Comparative = "Which is worse?" ; Correlation = "What goes together?" ; Distribution = "How spread out?" ; Geospatial = "Where?"
Data Characteristics
-
How much data is there?
-
At what speed and volume does it arrive?
-
How frequently is it updated?
-
How quickly is it processed?
-
What type of data is it? (Numerical: continuous/discrete, Categorical, Time-series, Geospatial)
-
Volume and velocity
- Historical analysis: Visualize a year's worth of sales data. Users can drill down by region and salesperson.
- Streaming Internet of Things (IoT) data: Visualize the real-time error rates of sensors in a factory.
-
Variety and veracity
- Structured data: A relational database is queried to report on customer service tickets that were submitted in a specific period.
- Unstructured data: Sentiment analysis is performed on customer service emails.
-
Value
- A business analyst uses periodic reports to showcase and report results to leadership.
- A DevOps engineer uses self-service dashboards to monitor and analyze performance in real time.
These are the "5 V's" of big data again (Volume, Velocity, Variety, Veracity, Value) — the data's personality decides which visualization tool fits.
Data Characteristics: Two Fraud Detection Use Cases
| Data characteristic considerations | Use case 1: Rule-Based (Batch Pipeline) | Use case 2: ML in Real Time (Streaming Pipeline) |
|---|---|---|
| How much data is there? | Millions of transactions (kilobytes to terabytes) | Millions of transactions (bytes to megabytes) |
| At what speed and volume is it arriving? | In predefined intervals (minutes to multiple days) | In real time (milliseconds to seconds) |
| How quickly is it processed? | Minutes to hours | Milliseconds to seconds |
| What type of data is it? | Structured and semistructured | Unstructured and semistructured data |
| What value do insights from the data provide? | Historical reporting of fraud cases — Reactive approach | Ability to detect fraud in real time — Proactive approach |
Batch = checking the security camera footage the next morning (reactive). Streaming = a security guard watching the live feed and stopping the thief at the door (proactive).
Access to Data
- Where does the data come from?
- Will the data need to be combined from multiple sources?
- Who needs access to the data and at what level? Who can access the tools?

- Amazon Athena ← used by:
- Data analyst → Data discovery
- Data engineer → SQL data query
- Tableau ← used by:
- Domain experts and business analysts → Perform analysis
- Data analyst or data scientist → Create visualizations
Example Workflow

- Data sources → Amazon S3 (raw storage) → Amazon EMR (processing) → Amazon S3 (processed) → Amazon Athena (query) → Tableau (visualize)
- Use Athena on the first S3 for one-time access to raw data
- Use Athena on the second S3 to query aggregated datasets → then send to Tableau
Types of Data Visualization Categories
- Common Types of Data Visualization Categories:
- Time-series
- Statistical
- Hierarchies
- Network
- Heat Map
- Map

Visualization Categories: Time-series
- It is one of the most common forms of data visualization. It documents sets of values over time — how it changes over time

Like a heart-rate monitor — the line goes up and down over time and you read the story from left to right.
Visualization Categories: Statistical
- Statistical distributions reveal trends based on how numbers are distributed. Common examples include histograms and box-and-whisker plots, which convey statistical features such as mean, median, and outliers
- Show how data is spread or concentrated

Visualization Categories: Hierarchies
- Many data sets, such as spatial entities of countries or common structures for governments, can be organized into natural hierarchies
- Represent data with parent-child relationships, nested structures, or organizational levels

- In a treemap: rectangle size = Total Population, rectangle color = ratio of elderly people (65+)
Like folders inside folders on your computer — the treemap shows each folder as a box, and bigger files take up bigger boxes.
Visualization Categories: Network
- Network visualization explores relationships, such as friendships and cliques. Three common types are force-directed layout, arc diagrams, and matrix view
- To show nodes (entities) and edges (relationships) in a connected structure, often revealing patterns like clusters, hubs, and flows

Like a social media friend map — each person is a dot (node), each friendship is a line (edge), and tight friend groups form clusters; the popular person connected to everyone is a hub.
Visualization Categories: Heat Map
- A heat map is a graphical representation of data where the individual values contained in a matrix are represented as colors
- Show patterns, density of data in a two-dimensional using color gradients. They are excellent for spotting hotspots, correlations, and anomalies

- Source: Understanding Tourist Behavior using Large-scale Mobile Sensing Approach: A case study of mobile phone users in Japan
Visualization Categories: Map
- Maps represent data in a geographic or spatial context. These are essential for location-based analytics and geospatial insights. Time and space can be depicted through the use of flow maps


Trajectory Map
- Shows four subjects' trajectories along with the type of trips made and locations of home and workplace
- Commuting trips are represented in blue, touristic trips are represented in red, and non-touristic trips are represented in green

Choosing the Right Chart: "What would you like to show?"

- COMPARISON
- Among Items
- Two variables per item → Column Chart Different Width
- One variable per item, many categories → Table with Embed Charts
- One variable per item, few categories:
- Many items → Bar Charts
- Few items → Column Chart
- Over Time
- Many periods:
- Cyclical data → Circular Area Chart
- Non-cyclical data → Single Line Chart
- Few periods:
- Many categories → Multiple Line Chart
- Few categories → Column Chart
- Many periods:
- Among Items
- DISTRIBUTION
- Single variable:
- Few points → Column Histogram
- Many points → Line Histogram
- Two variables → Scatter Plot
- Three variables → 3D Area Chart
- Single variable:
- COMPOSITION
- Change over time
- Few periods:
- Only relative differences matter → Stacked 100% Column Chart
- Relative and absolute differences matter → Stacked Column Chart
- Many periods:
- Only relative differences matter → Stacked 100% Area Chart
- Relative and absolute differences matter → Stacked Area Chart
- Few periods:
- Static over time
- Simple share of total → Donut Chart (pie)
- Accumulation or subtraction to total → Waterfall Chart
- Components of components → Stacked 100% Column Chart with Subcomponents
- Change over time
- RELATIONSHIP
- Two variables → Scatter Chart
- Three variables → Bubble Chart
Picking a chart is like picking a tool from a toolbox: first ask "what job?" (compare, distribute, compose, relate), then ask "how many things / how much time?" — the answer points to exactly one tool.
Why Data Visualization is Important?
1. Understand nature of data (Basic statistics)
- Taxi Indo Dataset: 2014-01-16 to 2014-04-14

- Location Error: 0.61% (lat, lon = 0)
2. Check quality of data / Error / Noise

3. Know scope and data availability (area)

4. Easy to understand in shortest time

5. Reveal hidden information to assist analysis
- RTIC LINK: Indo Taxi Data

- RTIC: Road Transport Information and Control
6. Allow to check correctness of the result

Visualization is like turning the lights on in a messy room: you immediately see what's there (nature), what's broken (errors), how big the room is (scope), and where something is missing (hidden info) — things you'd never spot by touch alone (reading raw numbers).
Characteristics of Effective Data Visualization
- Induce the viewer to think about meaning rather than about methodology, graphic design, the technology of graphic production or something else
- Avoid distorting what the data have to say
- Present many numbers in a small space
- Make large data sets coherent
- Encourage the eye to compare different pieces of data
- Reveal the data at several levels of detail, from a broad to the fine structure
- Serve a clear purpose: description, exploration, tabulation or decoration
- Be closely integrated with the statistical and verbal descriptions of a data set
Effective Data Visualization (Tips with Examples)
Tip 1: Know your audience
- What do they need to know? What is important to them?

Tip 2: Choose the right chart type
- Choose the right type of chart for data. Consider what is the most important takeaway that you need to convey? Exact values? Comparisons? Trends?

Tip 3: Use labels to clarify, not clutter
- Use text and labels to clarify, not clutter. A summary paragraph, a title, legend. All text and labels should be readable

Tip 4: Use color with purpose
- Use color to highlight important information or to differentiate or compare

Tip 5: Avoid misleading visualizations
- Avoid misleading visualizations. Always start with 0 on your axes. Never change the aspect ratio of your visualization

Tip 6: Keep it simple
- Keep your visualizations simple. Less is more. Remove information that doesn't have meaning to your audience

A truncated y-axis is like zooming a photo of a tiny pimple until it fills the screen — technically true, but it makes a small thing look like a disaster. Starting at 0 shows the real size.
Explore Data with Apache Zeppelin
- Apache Zeppelin = a web-based notebook that enables interactive data analytics (similar to Jupyter). You can make data-driven, interactive, collaborative documents with SQL, code and more
Final Result: Market Analysis for Bread Store
- Datasource: Bread Market data from https://www.kaggle.com/datasets/sulmansarwar/transactions-from-a-bakery
- Data Schema:
root
|-- Date: timestamp (nullable = true)
|-- Time: string (nullable = true)
|-- Transaction: integer (nullable = true)
|-- Item: string (nullable = true)- Total Data Records: 21293


Dataset: BreadBasket_DMS.csv
- File included with the lecture (21,293 data rows + 1 header row)
- Columns: Date, Time, Transaction, Item
Date,Time,Transaction,Item
2016-10-30,09:58:11,1,Bread
2016-10-30,10:05:34,2,Scandinavian
2016-10-30,10:05:34,2,Scandinavian
2016-10-30,10:07:57,3,Hot chocolate- One Transaction number can appear on multiple rows → one receipt with several items
Think of each row as one line on a bakery receipt — Transaction #2 bought two Scandinavian pastries, so it appears twice.
Zeppelin Setup Steps
Step 1: Get the data & upload to S3
- Download bread data from Kaggle or Google Classroom
- Upload file to S3

Step 2: Clone a new EMR cluster with Zeppelin
- Clone new EMR, make sure to select Zeppelin

- Zeppelin UI runs on port 8890
Step 3: Open Zeppelin
- Open Zeppelin, you will need to allow port 8890 in security group first
- You will see the page below if it works

Step 4: Create a new note
- Create new note with spark (Default Interpreter), then you will see a notebook similar to Jupyter

Step 5: Notebook interface
- Select language to use for each block section with the
%symbol

- First line of each block indicates the language:
%md= Markdown%pyspark= Use PySpark code%sql= Use SQL
- You can add multiple sections with same or different language

Zeppelin's
%tags are like switching the language on a translator app for each sentence — one paragraph in Markdown (notes), the next in Python, the next in SQL, all in one notebook.
Zeppelin Analysis Sections
- We will create multiple sections to analyze the data:
- Data source information
- Data Schema
- Total records
- Sample data
- Daily Transactions
- Top 5 Items
- Sales by Hour
- Sales by Day of Week
- Syntax:
%md= markdown,%pyspark= use pyspark,%sql= use sql
Data source information
%md
#### Data source: Bread Market data from https://www.kaggle.com/datasets/sulmansarwar/transactions-from-a-bakeryStart Connection
- Change to your S3 bucket in the path
%pyspark
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
BreadBasket=spark.read.format('csv').options(header='true',inferschema='true').load('s3://vis-data-51651/BreadBasket_DMS.csv')
BreadBasket.createOrReplaceTempView('bread_tb')header='true'→ first row is column namesinferschema='true'→ Spark guesses data types (e.g. Date → timestamp, Transaction → integer)createOrReplaceTempView('bread_tb')→ registers the DataFrame as a temporary SQL table so%sqlblocks can query it
Data Schema
%pyspark
BreadBasket.printSchema()root
|-- Date: timestamp (nullable = true)
|-- Time: string (nullable = true)
|-- Transaction: integer (nullable = true)
|-- Item: string (nullable = true)Total records
%pyspark
BreadBasket.count()- Output:
21293
Sample data (with SQL)
%sql
select * from bread_tb limit 5
Daily Transactions
%sql
select date, sum(Transaction) as total from bread_tb group by date order by date asc
- Display with line chart:
- Click the chart-type icons to select chart type (line chart)
- Click settings to show the settings panel
- Drag
dateinto keys → X-axis - Drag
totalinto values (SUM) → Y-axis - Tick Date format and enter
YYYY-MM-DDfor a custom date format (also options: force Y to 0, zoom)

Note:
sum(Transaction)adds up the transaction ID numbers, not a count of sales — so the values grow as IDs get bigger over time. Acount(distinct Transaction)would be the true number of receipts per day. (The lab usessumas given.)
Top 5 Items
%sql
select item, sum(transaction) as TotalSales
from bread_tb where item <> 'NONE' group by item order by TotalSales desc limit 5- Settings: keys =
item, values =TotalSales(SUM), chart = pie chart

Sales by Hour
%sql
select hour(time) as hour24, sum(transaction) as TotalSales
from bread_tb where item <> 'NONE' group by hour(time) order by hour24 asc
Sales by Day of Week
%sql
select date_format(Date, 'EEE') as week, sum(transaction) as TotalSales
from bread_tb where item <> 'NONE'
group by date_format(Date, 'EEE'),dayofweek(Date)
order by dayofweek(Date) ascdate_format(Date, 'EEE')→ short weekday name (Sun, Mon, …)dayofweek(Date)→ number 1–7 used only to sort days in calendar order (Sun first)

Run, titles, and report mode
- Run all (play button in the toolbar); run each block using Shift+Enter
- Show title of each section: paragraph gear menu → Show title (Ctrl+Alt+T)
- Report mode: display-mode dropdown (top right) →
default/simple/report

- Create the report by combining all scripts and view as report mode

Report mode is like switching from "edit" to "presentation" in PowerPoint — the code hides and only the titles and charts remain, ready to show your boss.
Explore Data with Tableau
- Steps overview:
- Prepare Data in Hive with S3 storage
- Download Hive ODBC driver: http://awssupportdatasvcs.com/bootstrap-actions/Simba/latest/
- Install Hive ODBC with 64bit version
- Allow port 10000 in security group
- Test connect in ODBC
- Connect to EMR Hive from Tableau
- Create visualization
Step 1: Prepare Data in Hive with S3 storage
- Create new bucket on S3 with folder (e.g.
data/)

- In Zeppelin, run command to create database in Hive and insert data (change to your S3)
%pyspark
spark.sql("CREATE DATABASE mydb LOCATION 's3://hivetb-515156/data'").show()
spark.sql("use mydb").show()
spark.sql("create table test as select * from bread_tb").show()- You should see a test folder in S3

Step 2: Download & install Hive ODBC driver
- Download Hive ODBC driver: http://awssupportdatasvcs.com/bootstrap-actions/Simba/latest/
- Install Hive ODBC with 64bit version

Step 3: Allow port 10000
- Allow port 10000 in security group (in your EMR) — this is the HiveServer2 port

Step 4: Test connect in ODBC (64bit)
- Fill in: Host and user: hadoop

Step 5: Connect to EMR Hive from Tableau
- In Tableau Connect → Amazon EMR Hadoop Hive
- Server: (EMR primary node public DNS)
- Port:
10000 - Authentication: Username
- Username:
hadoop - Transport: SASL

Step 6: Create visualization
- Search your table and drag to data source

- Create graph: Columns =
Item, Rows =SUM(Transaction)


ODBC is like a universal power adapter: Tableau has one "plug shape", Hive has another, and the ODBC driver sits in between so they can talk.
Lab Challenge: Explore Data with Glue, Athena, Tableau
- Check full info from Academy Data Engineering Capstone Project
- Use AWS Learner Lab to do this work

- Scenario: You have been tasked to create the infrastructure to host fishing data so that data analysts in your organization can create reports about fishing impact in the open seas. You have decided to build the infrastructure in your AWS account and test it by using three data files from the Sea Around Us dataset

- Open seas (high seas) = ocean areas not belonging to any country
- Exclusive Economic Zones (EEZs) = sea areas near a country's coast where that country has fishing rights
Overall Tasks
- Launch CloudShell as a development environment (IDE) instance
- Run SQL queries against a single file by using the Amazon S3 Select feature of Amazon Simple Storage Service (Amazon S3)
- Transform CSV-formatted data files to the Apache Parquet format and upload them to Amazon S3
- Create an AWS Glue crawler to infer the structure of the data
- Use Amazon Athena to query the data
- Create an Athena view
- Run queries on Athena view to analyze data
- Visualize data in Tableau
All services at the end

- Flow: User → CloudShell → data-source S3 bucket → Glue Crawler → Glue Data Catalog → Athena (+ query-results bucket) → Tableau
Glue crawler = a librarian who walks through your S3 "shelves", reads each file, and writes a catalog card (schema). Athena = the reading room where you ask SQL questions using that catalog. Tableau = the poster designer who turns the answers into charts.
Task 1: Configuring the Development Environment
Create buckets
- Create two S3 buckets:
data-source-#####,query-results-#####(same number suffix)

Launch CloudShell
- Launch CloudShell and turn on full screen mode

Download the data
- From the terminal run commands to download data
wget https://aws-tc-largeobjects.s3.us-west-2.amazonaws.com/CUR-TF-200-ACDSCI-1-91570/lab-capstone/s3/SAU-GLOBAL-1-v48-0.csv
wget https://aws-tc-largeobjects.s3.us-west-2.amazonaws.com/CUR-TF-200-ACDSCI-1-91570/lab-capstone/s3/SAU-HighSeas-71-v48-0.csv
wget https://aws-tc-largeobjects.s3.us-west-2.amazonaws.com/CUR-TF-200-ACDSCI-1-91570/lab-capstone/s3/SAU-EEZ-242-v48-0.csv
Inspect the data
- Check some data with
head -6 SAU-GLOBAL-1-v48-0.csv
year,fishing_entity,fishing_sector,catch_type,reporting_status,gear_type,end_use_type,tonnes,landed_value
1950,"Albania",Industrial,Discards,Unreported,bottom trawl,Direct human consumption,145.0013231580,212571.939749628
1950,"Albania",Industrial,Discards,Unreported,pelagic trawl,Direct human consumption,0.9863122230,1445.9337189179998
1950,"Albania",Industrial,Discards,Unreported,purse seine,Direct human consumption,0.4728285250,693.16661765
1950,"Albania",Industrial,Landings,Reported,bottom trawl,Direct human consumption,742.8529325409,1089022.3991050033
1950,"Albania",Industrial,Landings,Reported,bottom trawl,Other,0.7435965291,1090.11251161662- Analysis: Among other details, each line of data in this dataset includes:
- The year that the fishing occurred
- The country (fishing_entity) that did the fishing
- The tonnes of fish caught that year by that country
- The value in 2010 US dollars (landed_value) of the fish caught that year by that country
Convert CSV → Parquet
- Convert the
SAU-GLOBAL-1-v48-0.csvfile to Parquet format - Run
pip install pandas pyarrow fastparquetin the terminal (you can ignore errors) - Run the command to convert the file:
python3
import pandas as pd
df = pd.read_csv('SAU-GLOBAL-1-v48-0.csv')
df.to_parquet('SAU-GLOBAL-1-v48-0.parquet')
exit()
CSV vs Parquet: CSV is like a diary written line by line (row-based, plain text). Parquet is like a filing cabinet with one drawer per column, compressed — if you only need "tonnes", you open just that drawer. Faster and cheaper to query (Athena charges per data scanned).
Upload to S3
- To upload the
SAU-GLOBAL-1-v48-0.parquetfile to the data-source bucket:
aws s3 cp SAU-GLOBAL-1-v48-0.parquet s3://your_data_source_bucket/
- Note: the 63 MB CSV became a 9.2 MB Parquet file
Task 1.2: Querying a Single File with S3 Select
- In the Amazon S3 console, open the object → Object actions → Query with S3 Select

- Input settings: Format = Apache Parquet
- Amazon S3 Select does not support whole-object compression for Apache Parquet objects
- Output settings: Format = CSV, CSV delimiter = Comma

- Enter query:
SELECT fishing_entity, gear_type, tonnes FROM s3object s limit 10;
- S3 Select supports only the SELECT SQL command; using the S3 console you can extract up to 40 MB of records. For more complex SQL queries, use Amazon Athena
Task 2: Using an AWS Glue Crawler and Querying Multiple Files with Athena
- You will query data that is stored in multiple files. To do this, you will configure an AWS Glue crawler to discover the structure of the data and then use Athena to query the data (S3 Select supports only one file)
- We will download new data "SAU-HighSeas" that provides data in the Pacific area
Column comparison
| SAU-GLOBAL-1-v48-0 | SAU-HighSeas-71-v48-0 |
|---|---|
| area_name | |
| area_type | |
| year | year |
| scientific_name | |
| common_name | |
| functional_group | |
| commercial_group | |
| fishing_entity (country names) | fishing_entity |
| fishing_sector | fishing_sector |
| catch_type | catch_type |
| reporting_status | reporting_status |
| gear_type | gear_type |
| end_use_type | end_use_type |
| tonnes | tonnes |
| landed_value | landed_value |
- HighSeas has extra columns (area_name, area_type, scientific_name, common_name, functional_group, commercial_group); the shared columns line up
Convert & upload HighSeas
- Convert the
SAU-HighSeas-71-v48-0.csvfile to Parquet format and upload it to the data-source bucket
import pandas as pd
df = pd.read_csv('SAU-HighSeas-71-v48-0.csv')
df.to_parquet('SAU-HighSeas-71-v48-0.parquet')
exit()aws s3 cp SAU-HighSeas-71-v48-0.parquet s3://your_data_source_bucket/
Create Glue database
- Create an AWS Glue database:
fishdb(AWS Glue → Data Catalog → Databases → Add database)

Create Glue crawler
- Create an AWS Glue crawler:
fishcrawler(Crawlers → Add crawler → Set crawler properties → Name → Next)

- Data source configuration:
- "Is your data already mapped to Glue tables?" → Not yet
- Add a data source → Data source: S3, Location: In this account
- S3 path: select your S3 data source bucket (e.g.
s3://data-source-55514) - Subsequent crawler runs: Crawl all sub-folders

- IAM role: Select
CapstoneGlueRole

- Output configuration: Target database =
fishdb, Crawler schedule frequency = On demand

- Review and Create Crawler

Run the crawler
- Run the crawler to create a table that contains metadata in the AWS Glue database


- The crawler creates a table named after the bucket, e.g.
data_source_55514(hyphens → underscores)
Query with Athena
- To confirm that the table properly categorized the data, use Athena to run SQL queries against each column in the new table
- Athena → Launch query editor

- Athena pricing shown: $5.00 per TB scanned (SQL queries)
- Set query result location on S3 → Edit settings → select your query result bucket (e.g.
s3://query-results-55514) → Save


- Example query:
SELECT DISTINCT area_name FROM fishdb.data_source_55514;- The example query returns two results. For this column, every row in the dataset contains either the value "Pacific, Western Central" (for rows pulled from
SAU-HighSeas-71-v48-0.parquet) or a null value (for rows pulled fromSAU-GLOBAL-1-v48-0.parquet)

Because GLOBAL has no
area_namecolumn, Glue merges both files into one table and fills the missing column with NULL for GLOBAL rows. Soarea_name IS NULL≈ "this row came from the GLOBAL file".
Fiji — Pacific, Western Central high seas
- To find the value in US dollars of all fish caught by the country Fiji from the Pacific, Western Central high seas area since 2001, organized by year (change data source to yours):
SELECT year, fishing_entity AS Country, CAST(CAST(SUM(landed_value) AS DOUBLE) AS DECIMAL(38,2))
AS ValuePacificWCSeasCatch
FROM fishdb.data_source_55514
WHERE area_name LIKE '%Pacific%' and fishing_entity='Fiji' AND year > 2000
GROUP BY year, fishing_entity
ORDER By year
CAST(CAST(SUM(...) AS DOUBLE) AS DECIMAL(38,2))→ sums the values, then rounds to 2 decimal places (money format)
Fiji — all high seas (CAPTURE SCREEN)
- Find the value in US dollars of all fish caught by the country Fiji from all high seas areas since 2001, organized by year. In your output results, name the US dollar value column
ValueAllHighSeasCatch(change data source to yours)
SELECT year, fishing_entity AS Country, CAST(CAST(SUM(landed_value) AS DOUBLE) AS DECIMAL(38,2))
AS ValueAllHighSeasCatch
FROM fishdb.data_source_55514
WHERE ((area_name IS NULL) and (fishing_entity='Fiji') AND (year > 2000))
GROUP BY year, fishing_entity
ORDER By year
- CAPTURE SCREEN of this result (lab submission)
Create a view
- After you create and run the correct query and see the results displayed, create a view based on the query → Create → View from query → Name:
challenge

A view is a saved query that behaves like a virtual table — like a bookmark to a filtered spreadsheet. It stores no data itself; it re-runs the query each time you use it.
Task 3: Transforming a New File and Adding It to the Dataset
- You will add the
SAU-EEZ-242-v48-0.csvdata file to your dataset in Amazon S3 - This file has a few column names that don't match the data that you already added to your S3 bucket. However, the data in these columns does align with the existing data. You will need to modify the column names before you add the data to your bucket
| SAU-GLOBAL-1-v48-0 | SAU-HighSeas-71-v48-0 | SAU-EEZ-242-v48-0 |
|---|---|---|
| area_name | area_name | |
| area_type | area_type | |
| data_layer | ||
| uncertainty_score | ||
| year | year | year |
| scientific_name | scientific_name | |
| common_name | fish_name (mismatch) | |
| functional_group | functional_group | |
| commercial_group | commercial_group | |
| fishing_entity (country names) | fishing_entity | country (mismatch) |
| fishing_sector | fishing_sector | fishing_sector |
| catch_type | catch_type | catch_type |
| reporting_status | reporting_status | reporting_status |
| gear_type | gear_type | gear_type |
| end_use_type | end_use_type | end_use_type |
| tonnes | tonnes | tonnes |
| landed_value | landed_value | landed_value |
- Mismatched names:
fish_name→common_name,country→fishing_entity
Fix columns & convert with pandas
- Use the Python data analyst library, pandas, to fix the column names. In addition, convert the EEZ file to the Parquet format (do in Cloud9 / CloudShell)
cp SAU-EEZ-242-v48-0.csv SAU-EEZ-242-v48-0-old.csv
python3 # Start the python interactive shell
import pandas as pd
data_location = 'SAU-EEZ-242-v48-0-old.csv' # Load the backup version of the file
df = pd.read_csv(data_location) # Use Pandas to read the CSV into a dataframe
print(df.head(1))
df.rename(columns = {"fish_name": "common_name", "country": "fishing_entity"}, inplace = True)
print(df.head(1))
df.to_csv('SAU-EEZ-242-v48-0.csv', header=True, index=False)
df.to_parquet('SAU-EEZ-242-v48-0.parquet')
exit()cp ... -old.csvis a bash command (run beforepython3) → keeps a backup of the originalinplace = True→ modifiesdfdirectly instead of returning a copyindex=False→ don't write the pandas row index as an extra column
Upload & re-crawl
- Upload the new EEZ data file to the data-source bucket:
aws s3 cp SAU-EEZ-242-v48-0.parquet s3://your_data_source_bucket/
- Run Glue crawler again (so the table schema picks up the new file)

Verify & query
- Run query in Athena to verify the values in the
area_namecolumn (should see Fiji):
SELECT DISTINCT area_name FROM fishdb.data_source_#####;- To find the value in US dollars of all fish caught by Fiji from the open seas since 2001, organized by year:
SELECT year, fishing_entity AS Country, CAST(CAST(SUM(landed_value) AS DOUBLE) AS DECIMAL(38,2))
AS ValueOpenSeasCatch
FROM fishdb.data_source_#####
WHERE area_name IS NULL AND fishing_entity='Fiji' AND year > 2000
GROUP BY year, fishing_entity
ORDER By year- To find the value in US dollars of all fish caught by Fiji from the Fiji EEZ since 2001, organized by year:
SELECT year, fishing_entity AS Country, CAST(CAST(SUM(landed_value) AS DOUBLE) AS
DECIMAL(38,2)) AS ValueEEZCatch
FROM fishdb.data_source_#####
WHERE area_name LIKE '%Fiji%' AND fishing_entity='Fiji' AND year > 2000
GROUP BY year, fishing_entity
ORDER By year- To find the value in US dollars of all fish caught by Fiji from either the Fiji EEZ or the open seas since 2001, organized by year:
SELECT year, fishing_entity AS Country, CAST(CAST(SUM(landed_value) AS DOUBLE) AS
DECIMAL(38,2)) AS ValueEEZAndOpenSeasCatch
FROM fishdb.data_source_#####
WHERE (area_name LIKE '%Fiji%' OR area_name IS NULL) AND fishing_entity='Fiji' AND year > 2000
GROUP BY year, fishing_entity
ORDER By year- Logically: EEZ + Open seas = EEZ-and-open-seas, i.e.
Create the MackerelsCatch view
- Create a view in Athena, which will be useful to visualize the data
CREATE OR REPLACE VIEW MackerelsCatch AS
SELECT year, area_name AS WhereCaught, fishing_entity as Country, SUM(tonnes) AS TotalWeight
FROM fishdb.data_source_#####
WHERE common_name LIKE '%Mackerels%' AND year > 2014
GROUP BY year, area_name, fishing_entity, tonnes
ORDER BY tonnes DESC
- To view the following data: tonnes of mackerel caught by year by country
SELECT year, Country, MAX(TotalWeight) AS Weight
FROM fishdb.mackerelscatch GROUP BY year, Country
ORDER BY year, Weight DESC;- To view the MackerelsCatch for a particular country, e.g. China:
SELECT * FROM "fishdb"."mackerelscatch"
where country in ('China')
common_nameonly exists because we renamedfish_name→common_namein the EEZ file. Without that rename, EEZ mackerel rows would be missing from this view — that's why column names must match across files.
Task 4: Visualizing the Results in Tableau
Prepare
- Install Tableau (make sure to get license for student)
- Download ODBC driver for Athena: https://docs.aws.amazon.com/athena/latest/ug/odbc-v2-driver.html
- ODBC 2.0.3.0 versions available for Linux 64-bit, macOS (ARM), macOS (Intel), Windows 64-bit
- Prepare AWS Credential for connection (Learner Lab → AWS Details → AWS CLI credentials)
- Username =
aws_access_key_id - Password =
aws_secret_access_key - Session Token =
aws_session_token
- Username =

Connect via ODBC
- Open Tableau and connect using Other Databases (ODBC)
- Driver: Amazon Athena ODBC (x64) → Connect
- Amazon Athena ODBC Configuration:
- Region:
us-east-1 - Catalog:
AwsDataCatalog - Database:
default - Workgroup:
primary - S3 Output Location: change to your query result bucket configured in Athena (e.g.
s3://query-results-#####/)
- Region:
- Click Authentication Options to add credential

- Insert credential (make sure to get credential info from Learner Lab):
- Authentication Type: IAM Credentials
- Username =
aws_access_key_id, Password =aws_secret_access_key, Session Token =aws_session_token
- Click Test → make sure to see "Successfully connected"

Learner Lab credentials are temporary (session token) — like a day pass at a gym. When the lab session ends, you must copy new credentials into Tableau again.
Build the visualization
- Define data source by selecting table or view from AWS Athena
- Click the search icon to load table list
- Drag table (e.g.
mackerelscatch) to data source

- Create graph for your data — Total Weight by Year: Columns =
SUM(Total Weight), Rows =Year,Country, Color =Country

- Create another graph to show Total Weight by Country: Columns =
Country, Rows =SUM(Total Weight)

- Combine multiple graphs to a dashboard → click Enter Presentation mode

Summary
- Data Visualization
- Type of Visualization
- Why it is Important
- Effective Visualization
- Comparison
- Composition
- Distribution
- Relationship
- Explore data with
- Apache Zeppelin
- Tableau
- Lab Challenge
- Glue
- Athena
- Tableau
The whole lecture in one line: pick the right question → pick the right chart → build the pipeline (S3 → Glue → Athena) → draw it (Zeppelin / Tableau).