Module 4
Data Visualization
Data visualization uses charts, graphs and maps to present information clearly and
simply. It turns complex data into visuals that are easy to understand.
Importance of Data Visualization
Data visualization is essential for understanding and communicating information
effectively. Here are some key reasons why it's important:
1. Simplifies Complex Data: It turns large and complicated data into visual
formats like charts and graphs, making the information easier to understand.
2. Reveals Patterns and Trends: It helps identify trends, relationships, and
patterns that are not easily seen in raw data or tables.
3. Saves Time: Visuals allow quicker interpretation of data, helping users spot key
information at a glance instead of manually scanning through numbers.
4. Improves Communication: It makes it easier to explain data insights to others,
especially those who may not be familiar with the technical details.
5. Tells a Clear Story: Data visuals guide the audience through the information
step-by-step, making it easier to reach conclusions and make informed decisions.
Real-World Use Cases for Data Visualization
Data visualization is used across various industries to improve decision-making and
drive results. Here are a few examples:
1. Business Analytics: Used to monitor company performance, track KPIs, and
make data-driven decisions by visualizing trends, sales, and customer metrics.
2. Healthcare: Helps in analyzing patient records, tracking disease outbreaks, and
managing hospital operations through easy-to-read charts and dashboards.
3. Sports: Used to visualize player statistics, team performance, and match
outcomes, helping coaches and analysts improve strategies and training plans.
4. Retail and E-commerce: Enables tracking of sales, customer preferences, and
inventory levels, helping businesses adjust stock and marketing efforts
effectively.
Basic Charts for Data Visualization
1. Bar Charts
Bar charts are used to compare values across different categories using rectangular
bars. X-axis shows categories while Y-axis represents values. Common types
include horizontal, stacked and grouped bar charts.
Stacked Bar Chart
A stacked bar chart is ideal when you want to show how different categories
contribute to a whole. It stacks the bars on top of one another, allowing you to see
both the total value and the breakdown of each segment within the bar.
colors = c("green", "orange", "brown")
months <- c("Mar", "Apr", "May", "Jun", "Jul")
regions <- c("East", "West", "North")
Values <- matrix(c(2, 9, 3, 11, 9, 4, 8, 7, 3, 12, 5, 2, 8, 10, 11),
nrow = 3, ncol = 5, byrow = TRUE)
barplot(Values, main = "Total Revenue", [Link] = months, xlab =
"Month", ylab = "Revenue", col = colors)
legend("topleft", regions, cex = 0.7, fill = colors)
Histograms in R language
A graphical representation that manages a group of data points into different
specified ranges. It has a special feature that shows no gaps between the bars and is
similar to a vertical bar graph.
We can create histograms in R Programming Language using the hist() function.
Syntax:
hist(v, main, xlab, xlim, ylim, breaks, col, border)
Parameters:
v: A vector containing numerical values for the histogram.
main: The title of the chart.
col: The color of the bars.
xlab: The label for the x-axis.
border: The border color of each bar.
xlim: The range of values for the x-axis.
ylim: The range of values for the y-axis.
breaks: The width of each bar.
1. Creating a simple Histogram in R
Creating a simple histogram chart by using the above parameter. This vector v is
plot using hist().
LINE PLOT
A line graph is a type of chart that helps us visualize data through a series of points
connected by straight lines. It is commonly used to show changes over time, making
it easier to track trends and patterns. In a line graph, we plot data points on the X and
Y axes and connect them with lines, which helps us understand how values move
over time or across categories.
Creating Line Graphs in R
To create a line graph in R, we use the plot() function. This function allows us to
customize the graph with various parameters like the type of plot, color, labels, and
titles.
Syntax:
plot(v, type, col, xlab, ylab, main)
v: A vector containing the numeric values to be plotted.
type: Specifies the type of graph ("p" only points, "l" only lines, "o" both points
and lines).
xlab: Label for the x-axis.
ylab: Label for the y-axis.
main: Title of the chart.
col: Specifies the color for the points and lines.
Example:
In this example, we customize the graph by:
Coloring the line and points green.
Labeling the x-axis as "Month".
Labeling the y-axis as "Articles Written".
Adding the title "Articles Written Chart" to the graph.
v <- c(17, 25, 38, 13, 41)
plot(v, type = "o", col = "green", xlab = "Month", ylab =
"Articles Written", main = "Articles Written Chart")
PIE CHARTS
Pie charts are round charts divided into slices, where each slice shows a part of the
whole. The size of each slice represents its percentage.
When to Use:
To show how different parts contribute to a whole
To highlight a dominant category
Example
# Simple Pie Chart
slices <- c(10, 12,4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany", "France")
pie(slices, labels = lbls, main="Pie Chart of Countries")
3D Pie Chart
The pie3D( ) function in the plotrix</a > package provides 3D exploded pie charts.
# 3D Exploded Pie Chart
library(plotrix)
slices <- c(10, 12, 4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany", "France")
pie3D(slices,labels=lbls,explode=0.1,
main="Pie Chart of Countries ")
Scatter Chart (Plots)
Scatter charts use dots to show relationship between two numerical variables. X-axis
shows the independent variable and Y-axis shows the dependent variable.
When to Use:
To observe relationships between two variables
To detect patterns, clusters or outliers in data
Below is the example of scatter chart:
Syntax:
plot(x, y, main, xlab, ylab, xlim, ylim, axes)
Parameters:
x: Sets the horizontal coordinates.
y: Sets the vertical coordinates.
xlab: Label for the horizontal axis.
ylab: Label for the vertical axis.
main: Title of the chart.
xlim: Defines the x-axis range.
ylim: Defines the y-axis range.
axes: Indicates whether both axes should be drawn.
Example:
input <- mtcars[, c('wt', 'mpg')]
plot(x = input$wt, y = input$mpg,
xlab = "Weight",
ylab = "Milage",
xlim = c(1.5, 4),
ylim = c(10, 25),
main = "Weight vs Milage"
)
BOXPLOT
A boxplot (also known as a box-and-whisker plot) is used to visualize the
distribution of data based on five key statistics (minimum, first quartile (Q1),
median, third quartile (Q3), and maximum). They also show outliers and provide a
visual representation of how data is spread.
It displays the distribution of a dataset through its summary, which includes:
1. Minimum: The smallest data point, excluding outliers.
2. First Quartile (Q1): The median of the lower half of the dataset.
3. Median: The middle value of the dataset.
4. Third Quartile (Q3): The median of the upper half of the dataset.
5. Maximum: The largest data point, excluding outliers.
Creating a Boxplot in R
Boxplots are created in R by using the boxplot() function.
Syntax:
boxplot(x, data, notch, varwidth, names, main)
Parameters:
x: This parameter sets as a vector or a formula.
data: This parameter sets the data frame.
notch: This parameter is the label for horizontal axis.
varwidth: This parameter is a logical value. Set as true to draw width of the box
proportionate to the sample size.
main: This parameter is the title of the chart.
names: This parameter are the group labels that will be showed under each
boxplot.
Implementation of Box Plots in R
We will create box plots using an in built dataset in R programming language.
1. Importing Dataset
We use the data set "mtcars" , which is available in R language and explore the columns:
"mpg" and "cyl".
data(mtcars)
head(mtcars)
2. Creating the Boxplot
We will create the boxplot for the relationship between displacement and gear:
boxplot(disp ~ gear, data = mtcars,
main = "Displacement by Gear",
xlab = "Gear",
ylab = "Displacement")
Advanced data visualization Types
Heatmap
A heatmap() function in R Programming Language is used to plot a
heatmap. A heatmap is defined as a graphical representation of data using
colors to visualize the value of the matrix. It is used to represent more
common values or higher activities brighter colors reddish colors are used
and to less common or activity values darker colors are preferred. Heatmap
is also defined by the name of the shading matrix.
Syntax:
heatmap(data)
Parameters:
data: It represent matrix data, such as values of rows and columns
1. Create a Heatmap in R Programming Language
In this example, number of rows and columns are specified to draw heatmap
with a given function.
[Link](110)
data <- matrix(rnorm(100, 0, 5), nrow = 10, ncol = 10)
colnames(data) <- paste0("col", 1:10)
rownames(data) <- paste0("row", 1:10)
heatmap(data)
Mosaic Plots
Mosaic Plots are used to show symmetries for tables that are divided into two or
more conditional distributions. Mosaic plots are a great way to visualize hierarchical
data. A collection of rectangles represents all the elements to be visualized with the
rectangles of different sizes and colors makes a table, but what makes these mosaic
charts unique is the arrangement of the elements where there is a hierarchy those
elements are collected and labeled together, perhaps even with subcategories. So
mosaic plots can be used for plotting categorical data very effectively, with the area
of the data showing the relative proportions.
Syntax:
mosaic(x, shade=NULL, legend=NULL, main = NULL,..)
Parameters:
x: Here, x is pointing to the variable that holds the dataset/table. We passed our
dataset name here.
shade: shade is a boolean variable, if it is set to be true then we will get a
colored plot. Its default value is NULL.
legend: the legend is a boolean variable, if it is set to be true then we will be
able to see legends alongside our mosaic plot. Its default value is NULL.
main: main is a string variable, here we pass the title of our mosaic plot.
The package that is used for this is vcd (visualizing categorical data).
library('vcd')
# creating a random dataset
# creating 6 rows
data_values <- matrix(c(80, 10, 15,
70, 86, 18,
60, 30, 12,
90, 20, 25,
60, 96, 88,
50, 20, 32))
# creating dataset with above values
data <- [Link](
matrix(
data_values,
# specifying the number of rows
nrow = 6,
byrow = TRUE,
# creating two lists one for rows
# and one for columns
dimnames = list(
Random_Rows = c('A','B','C', 'D', 'E', 'F'),
Random_Columns = c('col_1', 'col_2', 'col_3')
)
)
)
# plotting the mosaic chart
mosaic(data,
# shade is used to plot colored chart
shade=TRUE,
# adding title to the chart
main = "A Mosaic Plot"
)
3D plot
3D plot in R Language is used to add title, change viewing direction, and add color
and shade to the plot. The persp() function which is used to create 3D surfaces in
perspective view. This function will draw perspective plots of a surface over the x–y
plane. persp() is defines as a generic function. Moreover, it can be used to
superimpose additional graphical elements on the 3D plot, by lines() or points(),
using the function trans3d().
Syntax:
persp(x, y, z)
Parameter: This function accepts different parameters i.e. x, y and z where x and y
are vectors defining the location along x- and y-axis. z-axis will be the height of the
surface in the matrix z.
Return Value: persp() returns the viewing transformation matrix for projecting 3D
coordinates (x, y, z) into the 2D plane using homogeneous 4D coordinates (x, y, z,
t).
Example 1: Simple Right Circular Cone
cone <- function(x, y){
sqrt(x ^ 2 + y ^ 2)
}
# prepare variables.
x <- y <- seq(-1, 1, length = 30)
z <- outer(x, y, cone)
# plot the 3D surface
persp(x, y, z)
CORRELOGRAM
A correlogram (or a correlation matrix plot or scatterplot matrix) is a
graphical display of the pairwise relationships between a group of variables.
In R Programming Language, there is a package called corrplot that makes it
simple to create correlograms. Below is an example of how to create a
correlogram in R using the corrplot package.
Correlograms using corrplot package in R
But first, we need to install 'corrplot' package in RStudio.
[Link]("corrplot")
Now we can use corrplot in our program.
[Link]('corrplot')
library(corrplot)
data(mtcars)
# Calculate the correlation matrix
cor_matrix = cor(mtcars)
# Create the correlogram
corrplot(cor_matrix, type = "upper",
method = "square",
[Link] = "black",
[Link] = "black", [Link] = 45)
Quantile-Quantile plot
A Quantile-Quantile plot is a graphical method for comparing two probability
distributions by plotting their quantiles against each other. Typically, it is used to
compare the distribution of the observed data with a theoretical distribution, such as
the normal distribution.
When to Use Q-Q Plot in R
Q-Q plots are often used in statistical analysis to:
Check for Normality: They help assess whether a dataset is approximately
normally distributed, which is a common assumption in many statistical tests.
Detect Skewness or Kurtosis: If the data has heavy tails or is skewed, this will
show up in the Q-Q plot.
Compare Two Distributions: It can be used to check if two datasets come from
the same distribution.
Implementation of Drawing Q-Q Plots in R
We are plotting Q-Q (Quantile-Quantile) plots to visually assess whether the sample
data comes from a theoretical distribution like normal, exponential or t-distribution.
1. Installing and Loading Required Packages
We install the ggplot2 package and load it to allow advanced Q-Q plotting.
[Link]: Installs external R packages.
library: Loads the installed package into the R session.
[Link]("ggplot2")
library(ggplot2)
2. Drawing a Basic Q-Q Plot Using qqnorm
We are using base R's qqnorm function to create a basic Q-Q plot with a reference
line.
rnorm: Generates random values from a normal distribution.
qqnorm: Creates a Q-Q plot against the normal distribution.
qqline: Adds a straight reference line to the Q-Q plot.
data <- rnorm(100)
qqnorm(data)
qqline(data, col = "blue")
Visualization of Geospatial Data
Geographic data visualization is a powerful way to explore and understand spatial
patterns and relationships. In R Programming Language, several packages are
available for creating maps and visualizing geographic data, including ggplot2,
leaflet, maps, maptools, and tmap. In this article, we'll explore how to visualize
geographic data in R using different packages, along with explanations and
examples.
Basic Maps with Maps Package
The maps package provides access to a wide range of geographic data, including
world maps, country maps, and more. Let's create a basic map of the world using
this package.
# Install and load the maps package
[Link]("maps")
library(maps)
# Create a basic world map
map("world")
Customizing Maps with ggplot2 Package
The ggplot2 package is a versatile tool for creating graphics in R. It can be used to
create customized maps with added layers and aesthetics.
First, We load the ggplot2 package.
Using map_data(), we load world map data into a dataframe.
We use ggplot() to create a plot object and specify the aesthetics.
geom_polygon() adds polygons to the plot, representing the map features.
coord_equal() ensures that the aspect ratio is preserved.
# Load the ggplot2 package
library(ggplot2)
# Load world map data
world_map <- map_data("world")
# Create a basic world map using ggplot2
ggplot(world_map, aes(x = long, y = lat, group = group)) +
geom_polygon(fill = "lightblue", color = "black") +
coord_equal()
Scale Component
The Scale Component in data visualization defines how data values are
mapped to graphical representations, such as the X and Y axes. It helps
in interpreting data accurately by adjusting how values are displayed on
a plot.
1. Linear Scale:
It is the default scale in most plots.
The distance between values is uniform, meaning equal changes
in data correspond to equal distances on the axis.
Suitable when data changes at a constant rate.
Example:
x <- 1:10
y <- x^2
plot(x, y, main = "Linear Scale", type = "b", col = "blue")
2. Logarithmic Scale:
Used when data covers a wide range or grows exponentially.
Converts values to their logarithmic form, making large ranges
easier to visualize.
Useful for identifying multiplicative relationships.
Example:
x <- 1:100
y <- x^2
plot(x, y, log = "xy", main = "Logarithmic Scale", type = "b", col =
"red")
Embellishing Components and Data Visualization Libraries
in R
Data visualization is an essential part of data analysis. It allows us to represent data
graphically so that patterns, trends, and relationships can be easily understood. In
R, we can enhance the readability and interpretability of visualizations by adding
embellishing components such as axes, labels, titles, legends, font styles, and
colors.
1. Axes
Axes are the lines that frame a graph and represent the scale of data values. The X-
axis usually represents the independent variable, while the Y-axis represents the
dependent variable. In R, axes are automatically added to most plots, but users can
customize their labels, limits, and style. Axes help viewers understand the range
and scale of data presented.
Example:
plot(1:10, (1:10)^2, type="b", xlab="X Values", ylab="Y = X^2")
2. Labels
Labels describe what the data in the plot represents. Axis labels indicate what each
axis stands for, while data labels can provide direct information about the data
points. Good labeling ensures that readers can interpret the chart without
confusion.
Example:
plot(1:10, (1:10)^2, xlab="Input (X)", ylab="Output (Y = X²)", main="Simple
Quadratic Plot")
3. Titles
A title provides a quick summary of what the graph is about. It helps the viewer
immediately understand the purpose or subject of the visualization. Titles should
be concise, descriptive, and placed at the top of the graph.
Example:
plot(1:10, (1:10)^2, main="Quadratic Relationship Between X and Y")
4. Legends
A legend identifies different categories, series, or groups represented by various
colors or symbols in a plot. It is essential when multiple data lines, bars, or
categories are displayed together. Legends help the viewer distinguish between
data series clearly.
Example:
x <- 1:10
y1 <- x^2
y2 <- x^3
plot(x, y1, type="l", col="blue", ylim=c(0, 1000),
xlab="X Values", ylab="Y Values", main="Comparison of X² and X³")
lines(x, y2, col="red")
legend("topleft", legend=c("X²", "X³"), col=c("blue", "red"), lty=1)
5. Font Size and Style
Font size and style play an important role in making a plot more readable. In R,
parameters like '[Link]', '[Link]', and '[Link]' control the size of titles, labels,
and axis text. Readable and consistent fonts make charts look professional and
clear.
Example:
plot(1:10, (1:10)^2, main="Font Size Example", [Link]=1.5, xlab="X",
ylab="Y", [Link]=1.2, [Link]=1)
6. Color
Colors are one of the most powerful embellishing components in data
visualization. They are used to differentiate between categories, highlight key
trends, and make graphs visually appealing. However, colors should be chosen
carefully to ensure clarity and accessibility (e.g., avoiding color combinations that
are hard for color-blind viewers).
Example:
barplot(c(10, 20, 30), [Link]=c("A", "B", "C"), col=c("skyblue", "orange",
"green"), main="Colored Bar Plot")
Data Visualization Libraries in R
R provides multiple libraries for creating various types of visualizations. The two
most popular systems are Base R graphics and ggplot2.
1. Base R Graphics
Base R graphics are the built-in plotting functions in R. They are simple to use and
suitable for quick, exploratory visualizations. Functions like plot(), hist(), barplot(),
and boxplot() are commonly used. Base R graphics allow adding titles, labels,
colors, and legends easily through function arguments.
Example:
hist(mtcars$mpg, col="lightblue", main="Histogram of MPG", xlab="Miles Per
Gallon")
2. ggplot2 Package
1. ggplot2
ggplot2 is the most popular and flexible visualization package in R. It is
based on the Grammar of Graphics and allows you to build complex
visualizations layer by layer.
Supports a wide range of plots scatter, bar, line, histogram, etc.
Layered syntax for adding components like titles, colors and themes.
Integrates well with data frames and the tidyverse ecosystem.
Best For: Creating high-quality static plots and handling large datasets with
structured visualization.
Example:
library(ggplot2)
ggplot(mtcars, aes(x=wt, y=mpg)) +
geom_point(color="blue") +
labs(title="Car Weight vs. Mileage", x="Weight", y="MPG")
3. Plotly
plotly brings interactivity to R visualizations. It can convert static plots from ggplot2 into
interactive web-based visuals.
Interactive zoom, hover and click features.
Supports 3D plots and dashboards.
Works seamlessly with ggplot2 and Shiny.
Best For: Building interactive dashboards and web visualizations.
Example:
library(plotly)
p <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point()
ggplotly(p)
OUTPUT:
3. lattice
lattice is one of the earliest R packages for data visualization, offering system for
creating multi-panel plots.
Designed for conditioning plots on factors (e.g., split by category).
Efficient for visualizing complex, grouped datasets.
Works well for exploratory data analysis (EDA).
Best For: Creating multi-variable comparative plots efficiently.
Example:
library(lattice)
xyplot(mpg ~ wt | cyl, data=mtcars, layout=c(3,1))
4. Highcharter
highcharter is a wrapper around the JavaScript-based Highcharts library, allowing
creation of interactive charts directly from R.
Highly customizable chart styles.
Interactive elements like tooltips, legends and animations.
Supports time series and financial visualizations.
Best For: Creating interactive web charts for reports and dashboards.
Example:
library(highcharter)
highchart() %>%
hc_add_series(mtcars$mpg, type="line", name="MPG")
How APIs Help in Collecting Messy Data
1. Provide Structured Data
APIs return data in structured formats like JSON or XML.
Even though the source (website, app, server) may contain huge and messy data,
the API organizes it so it becomes easier to extract.
2. Reduce Errors
APIs are designed for data access, so the information you receive is usually clean,
consistent, and updated—reducing manual extraction mistakes.
3. Access to Large & Real-Time Data
APIs allow downloading:
Live weather data
Stock market data
Social media data
Location data
E-commerce product data
This makes working with large and dynamic messy datasets possible.
4. Filter Data Automatically
APIs allow queries such as:
date ranges
product categories
keyword search
This helps collect only the required data, reducing noise.
How Web Scraping Tools Help in Collecting Messy Data
1. Extract Data from Any Web Page
Web scraping is used when the website does not provide an API.
It collects messy and unstructured data from:
HTML pages
Tables
Comments
Reviews
Blogs
News articles
2. Convert Unstructured Data to Structured Format
Scraping tools such as BeautifulSoup, Selenium, Scrapy, rvest (R) extract text,
links, images, product details, etc., and convert them into:
CSV
JSON
DataFrames
3. Handle Real-World Messy Data
Web scraping captures:
missing values
inconsistent formats
mixed text and numbers
duplicate or irrelevant information
This gives students realistic messy data for cleaning and wrangling.
4. Automate Large-Scale Data Collection
Scraping scripts can automatically:
navigate pages
scroll
click buttons
collect thousands of records
Which is useful for big data analysis.
Imp Questions
[Link] between Histogram and Scatter Plot. Mention the
functions used for their visualization in R.
[Link] Between Histogram and Bar plot.
[Link] data munging and data wrangling. Explain how APIs and web
scraping tools help in collecting messy data for analysis.
4. Explain the Concept of data visualization.
5. Explain advanced Data visualization Types.