0% found this document useful (0 votes)
6 views66 pages

Data Visualization Using R Lab Manual

The document is a lab manual for data visualization using R programming and Tableau, covering foundational concepts, data sources, and practical exercises for creating visualizations. It details the use of ggplot2 for R and provides comparisons with Tableau for creating various chart types, data manipulation, and formatting techniques. Additionally, it discusses advanced visualization techniques, including filtering, customizing tooltips, and data structuring.

Uploaded by

ruthwikreddy ace
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views66 pages

Data Visualization Using R Lab Manual

The document is a lab manual for data visualization using R programming and Tableau, covering foundational concepts, data sources, and practical exercises for creating visualizations. It details the use of ggplot2 for R and provides comparisons with Tableau for creating various chart types, data manipulation, and formatting techniques. Additionally, it discusses advanced visualization techniques, including filtering, customizing tooltips, and data structuring.

Uploaded by

ruthwikreddy ace
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

DATA VISUALIZATION - R PROGRAMMING/POWER BI LAB MANUAL

Program 1. Understanding Data, what is data, where to find data, Foundations for
building Data Visualizations, Creating Your First visualization?
Answer:

What is Data?

At its simplest, data is a collection of facts, observations, or measurements. In R, we usually work with
Tidy Data, where:

 Each variable is a column.


 Each observation is a row.
 Each value is a cell.

Where to Find Data?

You don't have to look far to find high-quality datasets for practice:

 Built-in R Datasets: R comes with practice data like mtcars, iris, and diamonds.
 Kaggle: The "social network" for data scientists with thousands of free datasets.
 UCI Machine Learning Repository: Great for technical and scientific data.
 TidyTuesday: A weekly social data project in the R community.

Foundations for Data Visualization


Before you write code, you need to understand the Grammar of Graphics. In R, this is handled by a
package called ggplot2. It views a chart as a series of layers:

1. Data: The actual information.


2. Aesthetics (aes): Mapping data to visual properties (X-axis, Y-axis, Color, Size).
3. Geometries (geom): The shape the data takes (Points, Bars, Lines).

Creating First Visualization


We will use the ggplot2 library and the built-in mpg dataset (which contains fuel economy data for
cars).

The Goal

We want to see if cars with bigger engines (displ) use more fuel on the highway (hwy).
The Source Code:

# 1. Install and load the necessary library

# [Link]("ggplot2") # Run this if you haven't installed it

library(ggplot2)

# 2. Look at the first few rows of the data

head(mpg)

# 3. Create the visualization

ggplot(data = mpg, aes(x = displ, y = hwy)) +


geom_point(aes(color = class)) + # Add points colored by car type
geom_smooth(method = "lm") + # Add a trend line
labs(title = "Engine Size vs. Highway Fuel Efficiency",
subtitle = "Larger engines generally get lower MPG",
x = "Engine Displacement (Liters)",
y = "Highway Miles per Gallon",
color = "Car Type") +
theme_minimal() # A clean, professional look

OUTPUT: Table Output (head(mpg))

This command shows the first few rows of the dataset. It helps you understand the columns (variables)
and the rows (observations) you are working with.

Based on the R code provided in the previous step, here is the simulated output. Since this
environment uses Python, I have recreated the mpg dataset and the visualization logic using Seaborn,
which follows a similar philosophy to R's ggplot2.
Program 2: Getting started with Tableau Software using Data file formats, connecting your Data to
Tableau, creating basic charts (line, bar charts, Tree maps), Using the Show me panel.

Answer: It seems there is a slight mix-up in the tools! Tableau and R are two different powerhouses in
the data world.

 Tableau is a "Drag-and-Drop" Business Intelligence (BI) tool.


 R is a "Code-Based" programming language.

Creating Basic Charts (Tableau vs. R)


Here is how you create the three charts you mentioned using the mpg dataset in R.

A. Bar Chart (Categorical Comparison)

In Tableau: Drag class to Columns and count to Rows. In R:

library(ggplot2)

# Bar chart of car classes


ggplot(mpg, aes(x = class)) +
geom_bar(fill = "steelblue") +
labs(title = "Frequency of Car Classes", x = "Type of Car", y = "Count") +
theme_minimal()
B. Line Chart (Trends Over Time)

In Tableau: Drag Year to Columns and a Measure to Rows. In R:

# Creating a summary for a line chart (Average efficiency over years)


library(dplyr)
mpg_summary <- mpg %>% group_by(year) %>% summarise(avg_hwy = mean(hwy))

ggplot(mpg_summary, aes(x = year, y = avg_hwy)) +


geom_line(size = 1, color = "darkred") +
geom_point() +
labs(title = "Average Highway MPG over Years", x = "Year", y = "Avg MPG")

C. Tree Map (Part-to-Whole)

In Tableau: Select a Dimension and a Measure, then click the Tree Map icon in "Show Me." In R:

# [Link]("treemapify")
library(treemapify)

ggplot(mpg, aes(area = displ, fill = manufacturer, label = manufacturer)) +


geom_treemap() +
geom_treemap_text(colour = "white", place = "centre", grow = TRUE) +
labs(title = "Tree Map of Engine Displacement by Manufacturer")

OUTPUT:
Program 3: Tableau Calculations, Overview of SUM, AVR, and Aggregate
features, Creating custom calculations and fields.
Answer:
Setting Up the Data

We will use the built-in mtcars dataset, which contains performance data for 32 automobiles.

R
# Load necessary library
library(dplyr)

# View the first few rows of the base data


head(mtcars)

Output:

| | mpg | cyl | disp | hp | drat | wt | ... |

| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |

| Mazda RX4 | 21.0 | 6 | 160 | 110 | 3.90 | 2.620 | ... |

| Mazda RX4 Wag | 21.0 | 6 | 160 | 110 | 3.90 | 2.875 | ... |

| Datsun 710 | 22.8 | 4 | 108 | 93 | 3.85 | 2.320 | ... |

Basic Aggregates: SUM and AVG (Mean)


Aggregation shrinks your data from many rows down to a summary. In R, we use group_by() to
define the categories and summarise() to perform the math.

R
# Calculate Total Horsepower (SUM) and Average MPG (AVG) per Cylinder group
summary_table <- mtcars %>%
group_by(cyl) %>%
summarise(
Total_HP = sum(hp),
Average_MPG = mean(mpg),
Car_Count = n()
)

print(summary_table)

Output:
| cyl | Total_HP | Average_MPG | Car_Count |

| :--- | :--- | :--- | :--- |

| 4 | 909 | 26.66 | 11 |

| 6 | 856 | 19.74 | 7 |

| 8 | 2929 | 15.10 | 14 |

Creating Custom Calculations (Row-Level)


If you want to create a new field (column) without collapsing the rows, you use mutate(). This is
common for creating ratios or unit conversions.

Example: Creating a Power-to-Weight Ratio

R
# Create a new custom field 'hp_per_wt'
mtcars_custom <- mtcars %>%
select(mpg, hp, wt) %>% # Selecting few columns for clarity
mutate(hp_per_wt = hp / wt)

head(mtcars_custom)

Output:

| | mpg | hp | wt | hp_per_wt |

| :--- | :--- | :--- | :--- | :--- |

| Mazda RX4 | 21.0 | 110 | 2.620 | 41.98 |

| Mazda RX4 Wag | 21.0 | 110 | 2.875 | 38.26 |

| Datsun 710 | 22.8 | 93 | 2.320 | 40.08 |

Logical Custom Fields (case_when)


In data visualization, we often need to "bin" or "label" data. This is how you create a custom categorical
field based on numerical logic.

R
# Labeling cars based on fuel efficiency
mtcars_labels <- mtcars %>%
mutate(efficiency_category = case_when(
mpg >= 25 ~ "High Efficiency",
mpg >= 18 & mpg < 25 ~ "Moderate",
mpg < 18 ~ "Low Efficiency"
))

# Let's see the count of our new custom field


table(mtcars_labels$efficiency_category)

Output:

| High Efficiency | Low Efficiency | Moderate |

| :--- | :--- | :--- |

| 6 | 15 | 11 |

Program 4: Applying new data calculations to your visualizations, Formatting


Visualizations, Formatting Tools and Menus, Formatting specific parts of the view.

Answer:

1. Drag and Drop Calculated Fields:

To apply your newly created calculated fields to a visualization, simply drag and drop them onto the
appropriate shelves in your worksheet. For example, you can drag a calculated field to the Rows or
Columns shelf, use it in filters, or place it on the Marks card to control the appearance of marks.
2. Filter with Calculated Fields:

Create filters using calculated fields to control which data points are displayed in your visualization.
You can use calculated fields to filter by specific criteria, such as a calculated date range or a custom
ranking.
Formatting Visualizations

Tableau provides a wide range of formatting options to make your visualizations more appealing and
informative:

1. Format Pane:

On the left side of the Tableau interface, you'll find the Format pane. It allows you to format various
aspects of your visualization, such as fonts, colors, lines, shading, and borders. Simply select the
element you want to format and use the options in the Format pane to make changes.
2. Marks Card:

The Marks card, located above your visualization, offers formatting options specific to the type of
marks you're using (e.g., color, size, label). Click on the Marks card to access these options and modify
how your data is represented.
3. Axis and Gridlines:

You can format axis labels, titles, and gridlines to improve the readability of your visualization. Right-
click on an axis or gridline to access formatting options.
4. Legends and Color Scales:

Customize legends and color scales to provide context for your visualizations. You can change colors,
labels, and the position of legends to match your data.
Formatting Tools and Menus

Tableau provides several formatting tools and menus to help you refine the appearance of your
visualizations:

1. Format Menu:

The Format menu at the top of the Tableau interface provides access to various formatting options,
including font styles, shading, borders, alignment, and more. You can use this menu to format text,
labels, and other elements.
2. Worksheet Menu:

In the Worksheet menu, you'll find options to format the entire worksheet, including background color,
borders, and worksheet title. You can also adjust the worksheet size.
3. Dashboard Menu:

If you're working with dashboards, the Dashboard menu allows you to format the entire dashboard
layout, including background, size, and title.
Formatting Specific Parts of the View

Tableau lets you format specific elements of your visualization:

1. Annotations:

You can add annotations to your visualizations to highlight important points or provide additional
context. Format these annotations using the options available when you right-click on an annotation.
2. Tooltips:

Customize tooltips to display relevant information when users hover over data points. You can format
tooltips to show or hide specific fields and control their appearance.
3. Headers and Titles:

Format headers, titles, and subtitles for clarity and consistency. Use the Format pane or the Format
menu to adjust text formatting, alignment, and shading.
Program 5: Editing and Formatting Axes, Manipulating Data in Tableau data, Pivoting Tableau data.

Answer:
Editing and Formatting Axes:
1. Edit Axis Title:
 Click on the axis title you want to edit.
 You can now modify the title text, font, size, color, and alignment using the Format pane or the
toolbar at the top.
2. Edit Axis Labels:
 Right-click on an axis and select "Edit Axis."
 In the Edit Axis dialog box, you can change the formatting of labels, tick marks, and other axis-
related properties.

3. Scale and Range:


 To change the scale or range of an axis, right-click on it and select "Edit Axis."
 In the dialog box, adjust the Minimum and Maximum values, scale, or range according to your
needs.
Manipulating Data in Tableau data

Change Data Type


If Tableau has inferred a wrong data type for a column, the data type can be changed
by clicking on the data type symbol in the column header
New Column(Calculated Fields)
Calculated fields can be used if you need to create customized logic for manipulating
certain data types or data values. There are a large-range of functions available in
Tableau that can used individually or collectively for data manipulation
Pivoting Tableau data
Data pivoting enables you to rearrange the columns and rows in a report so you can
view data from different perspectives
Program 6: Structuring your data, Sorting and filtering data, Pivoting data using R Code
Answer:

The process of getting your data ready for analysis is called Data Wrangling. While tools like Tableau
allow you to do this via a user interface, R uses the tidyverse suite of packages (primarily dplyr and
tidyr) to perform these operations with repeatable, transparent code.

1. Structuring Your Data (Tidy Data)


Data is well-structured when it follows the Tidy principle. This is the foundation for all modern R
programming:

1. Each variable is in its own column.


2. Each observation is in its own row.
3. Each value is in its own cell.

2. Sorting and Filtering Data


Filtering allows you to zoom in on specific data points, while sorting organizes them logically. In R, we
use filter() to pick rows and arrange() to sort them.
R Code Example:

Output: | | mpg | cyl | hp | wt |


| :--- | :--- | :--- | :--- | :--- |
|Lotus Europa | 30.4 | 4 | 113 | 1.513 |
|Mazda RX4 | 21.0 | 6 | 110 | 2.620 |
|Mazda RX4 Wag | 21.0 | 6 | 110 | 2.875 |
|Volvo 142E | 21.4 | 4 | 109 | 2.780 |
|Ferrari Dino | 19.7 | 6 | 175 | 2.770 |

3. Pivoting Data (Wide vs. Long)


Pivoting is one of the most important concepts in data visualization.

 Wide Data: Often used in Excel (e.g., columns for "Jan", "Feb", "Mar").
 Long Data: Required for R's ggplot2 and Tableau (e.g., one column for "Month", one for
"Sales").

R Code: Wide to Long

Output: | Product | Store_Location | Sales_Volume |


| :--- | :--- | :--- |
| Apples | Store_A | 100 |
| Apples | Store_B | 120 |
| Oranges | Store_A | 150 |
| Oranges | Store_B | 180 |

Program 7: Advanced Visualization Tools: Using Filters, Using the Detail panel, using the Size
panels, customizing filters, Using and Customizing tooltips, Formatting your data with colors.

Answer:

Here’s an Advanced Visualization Techniques in R, covering filters, detail layers, size aesthetics,
customized tooltips, and color formatting — primarily using R with ggplot2, dplyr, and plotly.

1️⃣ Using Filters in Visualizations


Filtering allows you to display only relevant subsets of data.

🔹 Static Filtering (Before Plotting)


Use dplyr to filter data before visualization:

library(ggplot2)
library(dplyr)

filtered_data <- mtcars %>%


filter(cyl == 6)

ggplot(filtered_data, aes(x = wt, y = mpg)) +


geom_point()

✅ Displays only 6-cylinder cars.

🔹 Dynamic Filtering (Interactive)


Using plotly for interactivity:

library(plotly)

p <- ggplot(mtcars, aes(x = wt, y = mpg)) +


geom_point()

ggplotly(p)

For dashboard-level filtering, use shiny:

library(shiny)

ui <- fluidPage(
selectInput("cyl", "Select Cylinders:",
choices = unique(mtcars$cyl)),
plotOutput("scatter")
)

server <- function(input, output) {


output$scatter <- renderPlot({
mtcars %>%
filter(cyl == input$cyl) %>%
ggplot(aes(wt, mpg)) +
geom_point()
})
}

shinyApp(ui, server)

2️⃣ Using the Detail Panel (Adding Granularity)


In R, “Detail” is handled by grouping aesthetics.

🔹 Grouping Data
ggplot(mtcars, aes(x = wt, y = mpg, group = cyl)) +
geom_line()

Or more clearly:

ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +


geom_point()

This adds detail by separating observations by cylinder count.

3️⃣ Using the Size Aesthetic


Size can represent a third numeric variable.

ggplot(mtcars, aes(x = wt, y = mpg, size = hp)) +


geom_point(alpha = 0.7)

Customize size scaling:

+ scale_size(range = c(2, 10))

Control legend:

+ guides(size = guide_legend(title = "Horsepower"))

4️⃣ Customizing Filters (Advanced Techniques)

🔹 Conditional Filtering Inside ggplot


ggplot(subset(mtcars, mpg > 20),
aes(wt, mpg)) +
geom_point()

🔹 Highlight Instead of Remove (Better Practice)


mtcars$highlight <- ifelse(mtcars$mpg > 20, "High MPG", "Low MPG")

ggplot(mtcars, aes(wt, mpg, color = highlight)) +


geom_point(size = 3)

This keeps full context while emphasizing key data.

5️⃣ Using and Customizing Tooltips (Interactive)


Tooltips are enhanced using plotly.
🔹 Basic Tooltip
p <- ggplot(mtcars,
aes(x = wt,
y = mpg,
text = paste("Car:", rownames(mtcars),
"<br>HP:", hp))) +
geom_point()

ggplotly(p, tooltip = "text")

🔹 Advanced Tooltip Formatting


p <- ggplot(mtcars,
aes(x = wt,
y = mpg,
text = paste0(
"<b>Car:</b> ", rownames(mtcars),
"<br><b>MPG:</b> ", mpg,
"<br><b>HP:</b> ", hp
))) +
geom_point()

ggplotly(p, tooltip = "text")

You can also customize with:

layout(hoverlabel = list(bgcolor = "white",


font = list(size = 14)))

6️⃣ Formatting Data with Colors


Color formatting improves readability and storytelling.

🔹 Categorical Colors
ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) +
geom_point(size = 3) +
scale_color_brewer(palette = "Set1")

🔹 Continuous Color Gradient


ggplot(mtcars, aes(wt, mpg, color = hp)) +
geom_point(size = 3) +
scale_color_gradient(low = "blue", high = "red")

🔹 Manual Custom Colors


ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) +
geom_point(size = 3) +
scale_color_manual(values = c("4" = "green",
"6" = "orange",
"8" = "red"))

🔹 Conditional Formatting
ggplot(mtcars, aes(wt, mpg)) +
geom_point(aes(color = mpg > 20), size = 3) +
scale_color_manual(values = c("TRUE" = "blue",
"FALSE" = "gray"))

🎯 Putting It All Together (Advanced Example)


library(ggplot2)
library(dplyr)
library(plotly)

data <- mtcars %>%


mutate(category = ifelse(mpg > 20, "Efficient", "Standard"))

p <- ggplot(data,
aes(x = wt,
y = mpg,
size = hp,
color = category,
text = paste("Car:", rownames(mtcars),
"<br>HP:", hp,
"<br>MPG:", mpg))) +
geom_point(alpha = 0.8) +
scale_size(range = c(3, 12)) +
scale_color_manual(values = c("Efficient" = "blue",
"Standard" = "red")) +
theme_minimal()

ggplotly(p, tooltip = "text")

This example demonstrates:

 Filtering logic
 Detail grouping
 Size encoding
 Custom tooltips
 Conditional color formatting
 Interactive visualization

OUTPUT:
Program 8: Creating Dashboards & Storytelling, creating your first dashboard and Story, Design
for different displays, adding interactivity to your Dashboard, Distributing & Publishing your
Visualization.

Answer:
Here is a complete, guide to Creating Dashboards & Storytelling in R, including:

 Creating your first dashboard


 Designing for different displays
 Adding interactivity
 Publishing & distributing
 Full working R code examples

We’ll use:

 R
 shiny
 shinydashboard
 ggplot2
 plotly
 flexdashboard

1️⃣ Creating Your First Dashboard (Shiny)

📌 Basic Shiny Dashboard Structure


# Install if needed
# [Link](c("shiny", "shinydashboard", "ggplot2", "dplyr", "plotly"))

library(shiny)
library(shinydashboard)
library(ggplot2)
library(dplyr)
library(plotly)

ui <- dashboardPage(
dashboardHeader(title = "Car Performance Dashboard"),

dashboardSidebar(
selectInput("cyl", "Select Cylinders:",
choices = unique(mtcars$cyl),
selected = 6),

sliderInput("hp",
"Minimum Horsepower:",
min = min(mtcars$hp),
max = max(mtcars$hp),
value = 100)
),

dashboardBody(
fluidRow(
box(width = 12,
plotlyOutput("scatterPlot"))
)
)
)

server <- function(input, output) {

filtered_data <- reactive({


mtcars %>%
filter(cyl == input$cyl,
hp >= input$hp)
})

output$scatterPlot <- renderPlotly({

p <- ggplot(filtered_data(),
aes(x = wt,
y = mpg,
size = hp,
color = factor(cyl),
text = paste("HP:", hp,
"<br>MPG:", mpg))) +
geom_point(alpha = 0.8) +
theme_minimal()

ggplotly(p, tooltip = "text")


})
}

shinyApp(ui, server)

✅ What This Dashboard Includes:

 Sidebar filtering
 Reactive filtering
 Interactive tooltip
 Size aesthetic
 Color grouping

2️⃣ Storytelling with Dashboards


Data storytelling = Context + Insight + Action.

🧠 Structure Your Story


Step 1: Overview (KPIs)

Add value boxes:

valueBoxOutput("avg_mpg")
Server:

output$avg_mpg <- renderValueBox({


valueBox(
round(mean(filtered_data()$mpg), 2),
"Average MPG",
icon = icon("car"),
color = "blue"
)
})

Step 2: Drill-down Visualization

Add tabs:

tabBox(width = 12,
tabPanel("Scatter Plot", plotlyOutput("scatterPlot")),
tabPanel("Distribution",
plotOutput("histPlot")))

Server:

output$histPlot <- renderPlot({


ggplot(filtered_data(), aes(mpg)) +
geom_histogram(bins = 10, fill = "steelblue") +
theme_minimal()
})

3️⃣ Design for Different Displays

📱 Responsive Layout Principles


 Use fluidRow() and column()
 Avoid fixed widths
 Limit clutter
 Increase font size for large displays

Example:

fluidRow(
column(6, plotlyOutput("scatterPlot")),
column(6, plotOutput("histPlot"))
)

🎨 Improve Visual Design


theme_minimal(base_size = 16) +
theme(
[Link] = element_text(face = "bold"),
[Link] = "bottom"
)

4️⃣ Adding Advanced Interactivity

🔹 Linked Filtering (Cross-filtering)


output$scatterPlot <- renderPlotly({
ggplotly(p) %>%
highlight("plotly_selected")
})

🔹 Dynamic UI
uiOutput("dynamic_ui")

Server:

output$dynamic_ui <- renderUI({


if (input$cyl == 8) {
sliderInput("wt", "Minimum Weight:",
min = 1, max = 6, value = 3)
}
})

🔹 Click Events
observeEvent(event_data("plotly_click"), {
click <- event_data("plotly_click")
print(click)
})

5️⃣ Creating Story Dashboards with Flexdashboard

📌 R Markdown Dashboard
Install:

[Link]("flexdashboard")

Create .Rmd file:

---
title: "Car Story Dashboard"
output:
flexdashboard::flex_dashboard:
orientation: rows
vertical_layout: fill
---

Example Content:
```{r}
library(ggplot2)
library(plotly)

Row
MPG vs Weight
p <- ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) +
geom_point()

ggplotly(p)

Run → Knit → Interactive dashboard.

---

⃣ Publishing & Distributing Your Dashboard


# 6️

## 🚀 Option 1: [Link] (Cloud Deployment)

Use:

```r
[Link]("rsconnect")
library(rsconnect)

rsconnect::setAccountInfo(name='yourname',
token='yourtoken',
secret='yoursecret')

rsconnect::deployApp()

Platform: [Link]

🚀 Option 2: RStudio Connect (Enterprise)


Deploy internally using:

rsconnect::deployApp()

Platform: RStudio Connect

🚀 Option 3: Export Static Dashboard


For flexdashboard:

Knit → HTML → Share HTML file

🚀 Option 4: Export Images


ggsave("dashboard_plot.png")

7️⃣ Professional Dashboard Best Practices


🎯 Storytelling Guidelines

 Start with KPIs


 Show trends
 Allow drill-down
 End with insight

🎨 Design Guidelines

 3–5 visuals per page


 Consistent color palette
 Avoid excessive legends
 Use whitespace

⚡ Performance Tips

 Use reactive() efficiently


 Avoid recalculating heavy operations
 Use req() for validation

8️⃣ Complete Professional Dashboard Template


Here is a clean enterprise-style structure:

dashboardPage(
dashboardHeader(title = "Executive Dashboard"),

dashboardSidebar(
sidebarMenu(
menuItem("Overview", tabName = "overview"),
menuItem("Details", tabName = "details")
)
),

dashboardBody(
tabItems(
tabItem(tabName = "overview",
fluidRow(
valueBoxOutput("avg_mpg"),
valueBoxOutput("avg_hp")
),
fluidRow(
box(width = 12, plotlyOutput("scatterPlot"))
)
),

tabItem(tabName = "details",
fluidRow(
box(width = 12, plotOutput("histPlot"))
)
)
)
)
)

OUTPUT:
Program 9: Tableau file types, publishing to Tableau Online, Sharing your visualizations,
printing, and Exporting.

Answer:

Below is a complete practical R workflow showing how to work with:

 Tableau file types


 Publishing to Tableau Online
 Sharing visualizations
 Printing dashboards
 Exporting PDF/PNG
Using R with Tableau and Tableau Online.

🔷 1️⃣ Tableau File Types & R Code

Common Tableau File Types


File Type Purpose R Can Generate?

.csv Data source ✅ Yes

.xlsx Excel data ✅ Yes

.hyper Tableau extract ✅ Yes (API)

.twb Workbook ❌ No

.twbx Packaged workbook ❌ No

R prepares data → Tableau builds visualization.

🔷 2️⃣ Export Data from R for Tableau

✅ Export CSV (Most Common Method)


# Load required package
library(dplyr)

# Prepare data
data <- mtcars %>%
mutate(
efficiency = ifelse(mpg > 20, "Efficient", "Standard"),
cyl = [Link](cyl)
)

# Export to CSV
[Link](data, "tableau_data.csv", [Link] = FALSE)

cat("CSV file created successfully.\n")

Output:

CSV file created successfully.

File created:

tableau_data.csv
✅ Export Excel File
[Link]("openxlsx") # Run once
library(openxlsx)

[Link](data, "tableau_data.xlsx")

cat("Excel file created successfully.\n")

File created:

tableau_data.xlsx

🔷 3️⃣ Create Tableau .hyper Extract from R


Install Tableau Hyper API package:

[Link]("tableauhyperapi")
library(tableauhyperapi)

Create Hyper Extract


library(tableauhyperapi)

hyper_file <- "[Link]"

# Start Hyper process


hyper_process <- HyperProcess$new()
connection <- Connection$new(hyper_process, hyper_file,
create_mode = CreateMode$CREATE_AND_REPLACE)

# Create table
connection$execute_command("
CREATE TABLE Cars (
mpg DOUBLE,
cyl INTEGER,
hp INTEGER,
wt DOUBLE
)")

# Insert data
for(i in 1:nrow(mtcars)) {
connection$execute_command(sprintf(
"INSERT INTO Cars VALUES (%f, %d, %d, %f)",
mtcars$mpg[i],
mtcars$cyl[i],
mtcars$hp[i],
mtcars$wt[i]
))
}

connection$close()
hyper_process$close()

cat("Hyper extract created successfully.\n")

File created:

[Link]

🔷 4️⃣ Publishing to Tableau Online via REST API


We use Tableau REST API from R.

Install required packages:

[Link](c("httr", "jsonlite"))
library(httr)
library(jsonlite)

🔐 Step 1: Authenticate
server <- "[Link]
api_version <- "3.18"

auth_body <- list(


credentials = list(
personalAccessTokenName = "YOUR_TOKEN_NAME",
personalAccessTokenSecret = "YOUR_TOKEN_SECRET",
site = list(contentUrl = "YOUR_SITE")
)
)

response <- POST(


paste0(server, "/api/", api_version, "/auth/signin"),
body = auth_body,
encode = "json"
)

auth_content <- content(response, as = "parsed")

token <- auth_content$credentials$token


site_id <- auth_content$credentials$site$id

cat("Authenticated successfully.\n")

📤 Step 2: Publish Hyper Data Source


publish_url <- paste0(
server,
"/api/", api_version,
"/sites/", site_id,
"/datasources"
)

publish_response <- POST(


publish_url,
add_headers("X-Tableau-Auth" = token),
body = upload_file("[Link]")
)

cat("Data source published to Tableau Online.\n")

🔷 5️⃣ Sharing Visualizations


After publishing a workbook in Tableau Online:

🔗 Open Dashboard in Browser


browseURL("[Link]
YourDashboard")

📧 Generate Share Link (Programmatic Output)


dashboard_url <-
"[Link]

cat("Share this dashboard link:\n")


cat(dashboard_url)

🔷 6️⃣ Printing Dashboard to PDF via API


view_id <- "YOUR_VIEW_ID"

pdf_url <- paste0(


server,
"/api/", api_version,
"/sites/", site_id,
"/views/", view_id,
"/pdf"
)

GET(
pdf_url,
add_headers("X-Tableau-Auth" = token),
write_disk("[Link]", overwrite = TRUE)
)

cat("Dashboard exported as PDF.\n")

File created:

[Link]
🔷 7️⃣ Export Dashboard as PNG Image
image_url <- paste0(
server,
"/api/", api_version,
"/sites/", site_id,
"/views/", view_id,
"/image"
)

GET(
image_url,
add_headers("X-Tableau-Auth" = token),
write_disk("[Link]", overwrite = TRUE)
)

cat("Dashboard exported as PNG image.\n")

File created:

[Link]

🔷 8️⃣ Complete Automated Workflow Script


# 1. Prepare Data
[Link](mtcars, "[Link]", [Link] = FALSE)

# 2. Create Hyper Extract (optional)

# 3. Authenticate to Tableau Online

# 4. Publish datasource

# 5. Export PDF copy

# 6. Share link

🔷 Enterprise Workflow Overview


R (Data Cleaning & Transformation)

CSV / Excel / Hyper Extract

Tableau Desktop or Tableau Online

Publish Dashboard

Share / Export / Print
Program 10: Creating custom charts, cyclical data and circular area charts, Dual Axis charts.

Answer:

Below is a complete guide to:

 ✅ Creating Custom Charts


 🔄 Cyclical Data & Circular Area Charts
 📊 Dual Axis Charts

Using R with ggplot2 and supporting libraries.

1️⃣ Creating Custom Charts in R


Custom charts go beyond basic bar/line charts by modifying:

 Shapes
 Themes
 Layers
 Scales
 Labels
 Annotations

✅ Example: Custom Lollipop Chart


# Install if needed
# [Link]("ggplot2")

library(ggplot2)

data <- [Link](


category = c("A", "B", "C", "D", "E"),
value = c(10, 25, 15, 30, 20)
)

ggplot(data, aes(x = reorder(category, value), y = value)) +


geom_segment(aes(xend = category, yend = 0), color = "gray") +
geom_point(size = 5, color = "steelblue") +
coord_flip() +
theme_minimal(base_size = 14) +
labs(title = "Custom Lollipop Chart",
x = "Category",
y = "Value")

What This Creates:

 Clean minimal design


 Horizontal layout
 Emphasis on values
 Custom styling

✅ Example: Custom Themed Scatter Plot


ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) +
geom_point(size = 4, alpha = 0.8) +
theme_minimal(base_size = 14) +
theme(
[Link] = element_text(face = "bold", size = 18),
[Link] = "bottom"
) +
labs(
title = "Car Efficiency vs Weight",
x = "Weight",
y = "Miles per Gallon",
color = "Cylinders"
)

2️⃣ Cyclical Data & Circular Area Charts


Cyclical data = Data that repeats over time:

 Months
 Hours
 Seasons
 Days of week

✅ Example: Cyclical Monthly Data


month_data <- [Link](
month = factor([Link], levels = [Link]),
sales = c(120, 140, 160, 180, 220, 250,
300, 280, 260, 200, 170, 150)
)

ggplot(month_data, aes(x = month, y = sales, group = 1)) +


geom_line(color = "steelblue", size = 1.2) +
geom_point(size = 3) +
theme_minimal(base_size = 14) +
labs(title = "Monthly Sales Trend",
x = "Month",
y = "Sales")

🔵 Circular Area Chart (Polar Area Chart)


Circular charts use coord_polar().

✅ Example: Circular Area Chart


ggplot(month_data, aes(x = month, y = sales, fill = month)) +
geom_bar(stat = "identity", width = 1) +
coord_polar() +
theme_minimal() +
theme([Link].y = element_blank(),
[Link] = element_blank(),
[Link] = element_blank()) +
labs(title = "Circular Area Chart - Monthly Sales")

What This Produces:

 Radial visualization
 Area proportional to value
 Cyclical perspective

🌙 Circular Line Chart (Radar-style)


ggplot(month_data, aes(x = [Link](month), y = sales)) +
geom_polygon(fill = "skyblue", alpha = 0.5) +
geom_line(color = "blue", size = 1) +
coord_polar() +
theme_minimal() +
labs(title = "Circular Sales Pattern")

3️⃣ Dual Axis Charts in R


Dual-axis charts display two variables with different scales.

⚠ Use carefully (can mislead).

✅ Example: Dual Axis Line Chart


library(scales)

dual_data <- [Link](


month = 1:12,
sales = c(120, 140, 160, 180, 220, 250,
300, 280, 260, 200, 170, 150),
profit = c(20, 25, 30, 40, 50, 60,
70, 65, 55, 45, 35, 30)
)

ggplot(dual_data, aes(x = month)) +


geom_line(aes(y = sales), color = "blue", size = 1.2) +
geom_line(aes(y = profit * 4), color = "red", size = 1.2) +
scale_y_continuous(
name = "Sales",
[Link] = sec_axis(~./4, name = "Profit")
) +
theme_minimal(base_size = 14) +
labs(title = "Dual Axis Chart: Sales vs Profit",
x = "Month")
Explanation:

 Profit multiplied by 4 for alignment


 Secondary axis rescales back
 Blue line → Sales
 Red line → Profit

🔁 Dual Axis Bar + Line Chart


ggplot(dual_data, aes(x = factor(month))) +
geom_bar(aes(y = sales), stat = "identity",
fill = "steelblue", alpha = 0.7) +
geom_line(aes(y = profit * 4, group = 1),
color = "red", size = 1.2) +
scale_y_continuous(
name = "Sales",
[Link] = sec_axis(~./4, name = "Profit")
) +
theme_minimal() +
labs(title = "Dual Axis: Bar (Sales) & Line (Profit)",
x = "Month")

OUTPUT:

You might also like