1.
Create a simple bar chart in R for categorical data
Aim:
To create a bar chart for categorical data in R.
Concept:
Bar charts are used to represent categorical data with rectangular bars. The
height of each bar shows the value of the category.
Code:
# Data for categories
sales <- c(120, 180, 90, 150)
products <- c("A", "B", "C", "D")
# Create bar chart
barplot(sales,
[Link] = products,
col = "skyblue",
main = "Product-wise Sales",
xlab = "Products",
ylab = "Sales")
Explanation:
barplot() draws vertical bars.
[Link] assigns category names.
col adds color.
Output Insight:
A bar chart showing each product’s sales comparison
2. Plot a histogram for a continuous variable (e.g., age or sales)
To visualize distribution of continuous data using a histogram.
Concept:
Histograms group continuous values into bins and show their frequency.
Code:
age <- c(20,22,25,30,35,40,42,28,32,26,38)
hist(age,
col="lightgreen",
main="Age Distribution",
xlab="Age",
ylab="Frequency",bin=5)
Explanation:
hist() divides the data into intervals (bins) and counts how many observations
fall into each.
Output Insight:
Histogram showing how many people fall into each age range.
3. Draw a simple line chart using plot()
To draw a line chart showing data trends over time.
Concept:
A line chart shows trends across continuous intervals (e.g., months or years).
Code:
months <- c("Jan","Feb","Mar","Apr","May")
sales <- c(100,150,130,180,200)
plot(sales, type="l", col="blue",
xlab="Months", ylab="Sales",
main="Monthly Sales Trend",xaxt="n")
axis(1, at=1:5, labels=months)
Explanation:
type="o" draws points and lines.
The line connects monthly sales values.
Output Insight:
Upward or downward trend of sales across months.
4. Create a scatter plot for two continuous variables
Aim:
To visualize the relationship between two continuous variables.
Concept:
A scatter plot helps detect correlation patterns.
Code:
height <- c(150,160,170,180,190)
weight <- c(50,55,65,72,80)
plot(height, weight,
col="red", pch=1,
cex=3,
xlab="Height (cm)",
ylab="Weight (kg)",
main="Height vs Weight")
Explanation:
pch=19 makes solid circles.
Points show how weight changes with height.
Output Insight:
Positive correlation between height and weight.
5. Draw a boxplot to show data variation
Aim:
To visualize data spread and detect outliers using a boxplot.
Concept:
A boxplot shows median, quartiles, and outliers.
Code:
marks <- c(45,50,55,60,62,70,75,80,90,95)
boxplot(marks,
col="orange",
main="Distribution of Marks",
ylab="Marks")
Explanation:
The box shows 50% of data (IQR).
Median is the line inside the box.
Output Insight:
Shows how marks vary among students.
6. Plot a pie chart using R for product-wise sales data.
Aim:
To display proportion of total sales per product.
Concept:
Pie charts represent parts of a whole as slices.
Code:
sales <- c(300, 450, 250, 500)
products <- c("Product A", "Product B", "Product C", "Product D")
# Create pie chart without labels
pie(sales,label=products,
col = rainbow(length(sales)),
main = "Sales Distribution")
# Add legend to the right side
legend("topright", # Position: "topright", "bottomleft", etc.
legend = products, # Legend text
fill = rainbow(length(sales)),# Match colors
cex = 0.8, # Text size
title = "Products") # Optional legend title
Explanation:
pie() divides circle into slices.
col=rainbow(4) assigns unique colors.
Output Insight:
Proportion of each product’s contribution to total sales
7. Demonstrate basics of plotting graphs and importance of colour
Aim:
To demonstrate different types of plots in R and to understand how the use of
colours enhances data visualization.
Concept:
Graphs are powerful tools for representing data visually.
Bar plots show comparisons among discrete categories.
Histograms display the frequency distribution of numerical data.
Line plots show trends or changes over a sequence or time.
Color plays a vital role in data visualization — it helps in:
Distinguishing between multiple data series or categories.
Making the graph visually appealing and easy to interpret.
Highlighting key patterns or anomalies in the dataset.
Code:
# Create simple data
x <- 1:5
y <- c(10, 15, 8, 12, 20)
# 1. Bar Plot
barplot(y,
col = "purple",
main = "Bar Plot Example",
xlab = "Categories",
ylab = "Values")
# 2. Histogram
hist(y,
col = "green",
main = "Histogram Example",
xlab = "Data Values",
ylab = "Frequency")
# 3. Line Plot
plot(x, y,
type = "l",
col = "red",
main = "Line Chart Example",
xlab = "X-axis",
ylab = "Y-axis")
Output Insight:
Bar Plot: Shows the height of each bar corresponding to each value in y.
The purple color visually differentiates the bars.
Histogram: Groups data into ranges (bins) and shows how frequently
data fall into each range. The green color helps easily identify the bins.
Line Plot: Connects data points to show trends across x values. The red
color line highlights the pattern of increase/decrease clearly.
Observation:
Each plot type represents the same data in a different way:
The bar plot focuses on comparison.
The histogram focuses on distribution.
The line chart focuses on trend or pattern.
Color enhances the interpretability by providing contrast and visual distinction.
Result:
Different types of plots can be created in R using built-in functions like barplot(),
hist(), and plot().
Using colors improves clarity, attractiveness, and comprehension of graphical
data representation
8. Write a program using R to demonstrate Importance of color in visualizations.
Controlling aesthetics like colour, size, legend and facets.
Aim
To demonstrate the importance of color and how to control various graphical
aesthetics such as color, size, legend, and facets using ggplot2 in R.
Concept / Theory
1. Color in Visualization:
o Makes data easier to interpret.
o Highlights categories, differences, and trends.
o Improves visual appeal and readability.
2. Aesthetics in ggplot2:
o color → changes outline or point color.
o fill → changes inside color of shapes (bars, boxes).
o size → controls size of points or lines.
o shape → changes point style (circle, triangle, etc.).
o facets → divide one plot into multiple small subplots based on a
categorical variable (like region or gear type).
What Are Facets?
Facets are a powerful feature in ggplot2 used to split a dataset into
subsets and draw one plot per subset automatically.
facet_wrap(~variable) → creates subplots for each value of the variable.
facet_grid(row_var ~ col_var) → creates a grid of plots based on two
variables.
Example:
If you plot cars data and facet by gear, you get one chart for 3-gear cars, one for
4-gear, and one for 5-gear.
Program
# Load ggplot2 library
[Link](ggplot2)
library(ggplot2)
# Use built-in dataset
data(mtcars)
# Create scatter plot with color, size, and facets
ggplot(mtcars, aes(x = mpg, y = hp,
color = factor(cyl), # Color by number of cylinders
size = wt)) + # Size by car weight
geom_point() + # Plot points
facet_wrap(~gear) + # Create subplots by gear type
labs(title = "Importance of Color and Aesthetic Controls in ggplot2",
x = "Miles Per Gallon (mpg)",
y = "Horsepower (hp)",
color = "Cylinders",
size = "Weight") +
theme_minimal() # Clean theme
Explanation of Code
Line Description
Loads ggplot2 package for advanced
library(ggplot2)
plotting.
Line Description
aes() Defines aesthetics: x, y, color, size.
color=factor(cy Each cylinder category gets a unique
l) color.
size=wt Heavier cars have larger points.
facet_wrap(~ge Creates separate plots for each gear
ar) type.
labs() Adds titles and axis labels.
theme_minimal
Simplifies background for clarity.
()
Output Insight
The plot shows multiple small charts (facets), one for each gear value (3,
4, 5).
Within each subplot:
o Color distinguishes cars by number of cylinders.
o Size represents car weight.
A legend automatically appears explaining color and size meanings.
This clearly demonstrates how color and size enhance data understanding and
facets provide category-wise comparisons.
Result
Successfully demonstrated the use of color, size, legend, and facets in
ggplot2 to enhance visual analytics.
9. Write a program using R to demonstrate Functions in R for plotting, plots with
one categorical variable, plots with one continuous variable, plots with one
categorical and one continuous variable.
Aim
To demonstrate different built-in R plotting functions for:
One categorical variable
One continuous variable
One categorical and one continuous variable
Concept / Theory
R provides several functions for data visualization:
Typical
Case Purpose
Function
One categorical variable barplot() Frequency comparison
One continuous variable hist() Distribution pattern
Typical
Case Purpose
Function
One categorical + one Compare variation across
boxplot()
continuous variable categories
These help us understand data type relationships visually.
Program
# -----------------------------
# 1. Plot with one categorical variable
# -----------------------------
products <- c("A", "B", "C", "D")
sales <- c(150, 200, 120, 180)
barplot(sales,
[Link] = products,
col = "skyblue",
main = "Bar Plot - Categorical Variable (Products)",
xlab = "Product",
ylab = "Sales")
# -----------------------------
# 2. Plot with one continuous variable
# -----------------------------
height <- c(150, 160, 165, 170, 172, 175, 180, 185)
hist(height,
col = "lightgreen",
main = "Histogram - Continuous Variable (Height)",
xlab = "Height (cm)",
ylab = "Frequency")
# -----------------------------
# 3. Plot with one categorical and one continuous variable
# -----------------------------
# Using the built-in mtcars dataset
boxplot(mpg ~ cyl, data = mtcars,
col = c("orange", "yellow", "lightblue"),
main = "Boxplot - MPG by Number of Cylinders",
xlab = "Cylinders",
ylab = "Miles per Gallon (mpg)")
Explanation of Code
Functio
Description
n
barplot() Displays categorical data (Products vs Sales).
hist() Shows distribution of continuous data (Height).
boxplot( Compares MPG across different cylinder groups in the mtcars
) dataset.
mpg ~
Formula notation — plots MPG for each cylinder category.
cyl
Output Insight
1. Bar Plot: Blue bars comparing sales among four products.
2. Histogram: Green bars showing how heights are distributed.
3. Boxplot: Orange/yellow/blue boxes comparing car mileage across 4, 6, 8-
cylinder engines.
10. Write a program using R to demonstrate Plots with two
continuous variables, controlling various aesthetics of the graph.
Two continuous variables can be plotted using a scatter plot.
In R, the ggplot2 package allows us to modify aesthetics (visual
appearance) using the aes() function.
Common aesthetics:
o color → represents categories or values by color
o size → represents magnitude or weight
o shape → differentiates categories (optional)
This enhances readability and adds more information to the same plot.
ggplot(mtcars, aes(x = mpg, y = hp,
color = wt, # continuous color scale based on weight
size = qsec)) + # size of points based on quarter mile time
geom_point(shape = 19, alpha = 0.5) + # filled circles with
transparency
labs(title = "Scatter Plot of Horsepower vs Mileage",
x = "Miles per Gallon (mpg)",
y = "Horsepower (hp)",
color = "Weight",
size = "Quarter Mile Time") +
theme_minimal()
Line Description
ggplot(mtcars, aes(x = Initializes a ggplot object with two continuous
mpg, y = hp)) variables (Mileage & Horsepower).
color = wt Color of each point represents car weight.
Size of points represents the quarter-mile
size = qsec
acceleration time.
geom_point() Draws scatter plot points.
alpha = 0.7 Adds transparency to avoid overlap.
labs() Adds title and axis labels.
theme_minimal() Sets a clean background.
The scatter plot shows the relationship between Mileage (mpg) and
Horsepower (hp).
Points are:
Colored by weight (wt) — heavier cars are darker.
Sized by acceleration time (qsec).
You can see an inverse relationship: higher horsepower → lower
mileage.
11. Write a program using R to demonstrate understanding the
philosophy of ggplot2, bar plot, pie chart, histogram, boxplot,
scatter plot and regression plots.
Aim
To understand the philosophy of ggplot2 and demonstrate commonly used
plots — bar plot, pie chart, histogram, boxplot, scatter plot, and
regression plot — using R.
🧠 Concept / Theory
🔹 Philosophy of ggplot2: The Grammar of Graphics
ggplot2 is based on "The Grammar of Graphics" — a system for
building graphics layer by layer.
Each visualization is built from data, aesthetic mappings, and
geometric objects (geoms).
This approach allows flexible, structured, and consistent plotting.
Basic structure of any ggplot:
ggplot(data, aes(x, y)) + geom_<type>() + additional_layers
Common geoms:
Plot Type Function
Bar Plot geom_bar()
Histogram geom_histogram()
Boxplot geom_boxplot()
Scatter Plot geom_point()
Regression geom_smooth(method="
Line lm")
💻 Program
# Load ggplot2
library(ggplot2)
# 1. Bar Plot
data_bar <- [Link](Product = c("A", "B", "C", "D"),
Sales = c(120, 180, 90, 160))
ggplot(data_bar, aes(x = Product, y = Sales, fill = Product)) +
geom_bar(stat = "identity") +
labs(title = "Bar Plot - Product Sales") +
theme_minimal()
# 2. Pie Chart
data_pie <- [Link](
Category = c("A", "B", "C", "D"),
Sales = c(120, 180, 90, 160)
)
ggplot(data_pie, aes(x = "", y = Sales, fill = Category)) +
geom_bar(stat = "identity", width = 1) +
coord_polar("y", start = 0) +
labs(title = "Pie Chart - Sales Distribution") +
theme_void()
# 3. Histogram
ggplot(mtcars, aes(x = mpg)) +
geom_histogram(fill = "skyblue", color = "black", bins = 10) +
labs(title = "Histogram - Distribution of Mileage (mpg)",
x = "Miles per Gallon", y = "Frequency") +
theme_minimal()
# 4. Boxplot
ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = factor(cyl))) +
geom_boxplot() +
labs(title = "Boxplot - MPG by Number of Cylinders",
x = "Cylinders", y = "Miles per Gallon") +
theme_minimal()
# 5. Scatter Plot
ggplot(mtcars, aes(x = hp, y = mpg, color = factor(cyl))) +
geom_point(size = 3) +
labs(title = "Scatter Plot - Horsepower vs Mileage",
x = "Horsepower", y = "Miles per Gallon") +
theme_minimal()
# 6. Regression Plot (Scatter with Trend Line)
ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point(color = "blue") +
geom_smooth(method = "lm", color = "red") +
labs(title = "Regression Plot - MPG vs Horsepower",
x = "Horsepower", y = "Miles per Gallon") +
theme_minimal()
🧾 Explanation of Code
Ste
Plot Type Description
p
1 Bar Plot Displays product-wise sales using vertical bars.
Uses coord_polar() to convert bar chart to circular
2 Pie Chart
form.
3 Histogram Shows frequency distribution of mpg (continuous
Ste
Plot Type Description
p
variable).
4 Boxplot Compares MPG across cylinder categories.
5 Scatter Plot Plots relationship between horsepower and mileage.
Regression Adds regression line (geom_smooth(method="lm"))
6
Plot to scatter plot for trend analysis.
📊 Output Insight
Bar Plot: Compares product sales with distinct colors.
Pie Chart: Displays each product’s contribution to total sales.
Histogram: Shows how car mileage is distributed.
Boxplot: Shows variation and outliers across cylinder types.
Scatter Plot: Visualizes relationship between horsepower and fuel
efficiency.
Regression Plot: Shows negative trend — higher horsepower, lower
MPG.
12.G
Aim
To create a histogram in R using the ggplot2 package for visualizing the
distribution of sales data.
🧠 Concept / Theory
A histogram displays the frequency distribution of a continuous
variable.
It divides data into bins (intervals) and counts how many values fall
within each bin.
In ggplot2, the function geom_histogram() is used.
The histogram helps to understand data spread, central tendency,
and skewness.
Syntax:
ggplot(data, aes(x = variable)) + geom_histogram()
sales_data <- [Link](Sales = c(120, 150, 130, 180, 200, 250, 300,
220, 270, 290, 320, 350, 400, 380, 410))
# Create histogram using ggplot2
ggplot(sales_data, aes(x = Sales)) +
geom_histogram(fill = "skyblue", color = "black", bins = 8) +
labs(title = "Histogram Showing Distribution of Sales Data",
x = "Sales Amount",
y = "Frequency") +
theme_minimal()
Function Description
ggplot(sales_data, aes(x = Initializes ggplot and defines the variable for
Function Description
Sales)) the x-axis.
geom_histogram() Creates the histogram.
fill, color Sets bar color and border color.
bins = 8 Divides the data range into 8 intervals.
labs() Adds title and axis labels.
theme_minimal() Applies a clean, simple theme.
Output Insight
The histogram displays how sales values are distributed across different
ranges.
The height of each bar represents the number of observations
(frequency) within that range.
You can easily see if sales are concentrated in low, medium, or high
values.
[Link]
Aim
To develop a scatter plot showing the relationship between two continuous
variables and add a regression line using geom_point() and geom_smooth()
in ggplot2.
Concept / Theory
A scatter plot shows the relationship or correlation between two
continuous variables.
A regression line represents the trend or best-fit line through the data
points.
In ggplot2, we use:
o geom_point() → to plot the data points.
o geom_smooth(method = "lm") → to add a linear regression line.
Syntax:
ggplot(data, aes(x, y)) + geom_point() + geom_smooth(method = "lm")
Program
# Load the ggplot2 package
library(ggplot2)
# Create sample dataset
data <- [Link](
Sales = c(100, 120, 150, 170, 200, 230, 250, 270, 300, 320),
Profit = c(20, 25, 28, 32, 40, 43, 45, 50, 55, 58)
)
# Create scatter plot with regression line
ggplot(data, aes(x = Sales, y = Profit)) +
geom_point(color = "blue", size = 3) + # Scatter points
geom_smooth(method = "lm", color = "red", se = TRUE) + # Regression
line
labs(title = "Scatter Plot with Regression Line",
x = "Sales Amount",
y = "Profit Amount") +
theme_minimal()
Explanation of Code
Function / Parameter Description
geom_point() Plots each (Sales, Profit) point as a blue dot.
geom_smooth(method = Adds a linear regression line (method = "lm"
"lm") means linear model).
Adds a shaded region showing confidence
se = TRUE
interval.
labs() Adds title and axis labels.
theme_minimal() Applies a clean and simple visual style.
Function / Parameter Description
Output Insight
Blue points represent the data (Sales vs Profit).
A red line shows the trend — as Sales increase, Profit also increases
(positive correlation).
The shaded region represents the confidence interval of the regression
fit
14.
Aim
To create a bar chart grouped by a categorical variable and display separate
subplots for each category using facet_wrap() in ggplot2.
Concept / Theory
A bar chart represents categorical data using rectangular bars.
Faceting allows you to split one plot into multiple panels (subplots),
each showing data for a subset of the variable.
facet_wrap(~variable) automatically creates one plot for each level of the
given variable.
Why use facet_wrap()?
It helps compare subcategories (like different “gear” types or “regions”)
visually.
Keeps all plots consistent in scale and style.
Program
# Load the ggplot2 library
library(ggplot2)
# Use built-in dataset
data(mtcars)
# Convert numeric columns to factors for grouping
mtcars$cyl <- [Link](mtcars$cyl)
mtcars$gear <- [Link](mtcars$gear)
# Create bar chart grouped by gear and faceted by cylinders
ggplot(mtcars, aes(x = gear, fill = gear)) +
geom_bar() +
facet_wrap(~cyl) +
labs(title = "Bar Chart Grouped by Gear, Faceted by Cylinders",
x = "Gear Type",
y = "Count of Cars",
fill = "Gear") +
theme_minimal()
Explanation of Code
Function /
Description
Code
Creates bars representing count of cars for each gear
geom_bar()
type.
fill = gear Assigns color to bars based on gear type.
facet_wrap(~c Creates separate plots (facets) for each cylinder type
yl) (4, 6, 8).
labs() Adds title and axis labels.
theme_minimal
Applies a clean background style.
()
Output Insight
The chart shows three panels (facets) — one each for cars with 4, 6,
and 8 cylinders.
Within each facet, bars represent counts of cars grouped by gear type
(3, 4, or 5).
Colors distinguish different gear types.
Makes it easy to compare gear distribution across cylinder categories.
15.
Aim
To create a simple R visualization that applies color encoding to represent
different categories in data using ggplot2.
Concept / Theory
Color encoding helps distinguish categories visually, improving clarity
and understanding.
In ggplot2, the color or fill aesthetic is used to apply different colors to
each category.
o color → outlines or points.
o fill → fills shapes (bars, boxes, etc.).
Helps in identifying patterns or group differences instantly.
Program
# Load the ggplot2 package
library(ggplot2)
# Create sample dataset
data <- [Link](
Product = c("A", "B", "C", "D", "E"),
Sales = c(200, 250, 180, 300, 220),
Region = c("North", "South", "East", "West", "North")
)
# Create bar chart with color encoding for regions
ggplot(data, aes(x = Product, y = Sales, fill = Region)) +
geom_bar(stat = "identity") +
labs(title = "Sales by Product (Color Encoded by Region)",
x = "Product",
y = "Sales",
fill = "Region") +
theme_minimal()
Explanation of Code
Component Description
aes(x = Product, y = Sales,
Maps the Region variable to different colors.
fill = Region)
geom_bar(stat = "identity") Creates bars with actual sales values.
Assigns unique colors for each category in
fill
the “Region” column.
Component Description
theme_minimal() Uses a clean and simple theme.
Output Insight
A colored bar chart with Products (A–E) on the X-axis and Sales on the
Y-axis.
Each bar is filled with a unique color representing its Region.
The legend automatically shows color–region mapping.
This demonstrates how color encoding helps to quickly differentiate
categories.
16.
Aim
To demonstrate how to customize plot aesthetics such as color, shape,
and size using the ggplot2 package in R.
Concept / Theory
In ggplot2, aesthetics (aes()) define how data variables are mapped to
visual properties.
You can customize:
o Color: Distinguish categories by color.
o Shape: Use different symbols for categories (useful for scatter
plots).
o Size: Represent magnitude or another continuous variable.
This makes plots more informative and visually appealing.
Common aesthetics:
Aesthet
Used For Example
ic
color =
color Outline or point color
factor(cyl)
fill =
fill Fill color (for bars, boxes)
factor(gear)
shape =
shape Different symbols
factor(am)
Point size (continuous
size size = wt
variable)
Program
# Load ggplot2
library(ggplot2)
# Use built-in dataset
data(mtcars)
# Convert numeric variables to factors for color/shape grouping
mtcars$cyl <- [Link](mtcars$cyl)
mtcars$gear <- [Link](mtcars$gear)
# Create customized scatter plot
ggplot(mtcars, aes(x = mpg, y = hp,
color = cyl, # Color by cylinders
shape = gear, # Shape by gear type
size = wt)) + # Size by car weight
geom_point(alpha = 0.8) +
labs(title = "Customized Aesthetics in ggplot2",
x = "Miles per Gallon (mpg)",
y = "Horsepower (hp)",
color = "Cylinders",
shape = "Gear Type",
size = "Weight (1000 lbs)") +
theme_minimal()
Explanation of Code
Code Description
Assigns distinct colors to cylinder groups (4,
color = cyl
6, 8).
Uses different point shapes for each gear
shape = gear
type.
size = wt Scales point size according to car weight.
geom_point(alpha=
Plots semi-transparent points.
0.8)
Adds custom titles, axis labels, and legend
labs()
titles.
theme_minimal() Applies a clean layout for readability.
Output Insight
X-axis: Mileage (mpg)
Y-axis: Horsepower (hp)
Color: Cylinder group
Shape: Gear type
Size: Car weight
Each point shows a car; visual cues (color, shape, size) make category and
magnitude differences instantly visible.