In the previous module, you learned how to perform basic statistical analysis in R. You calculated totals, averages, medians, minimums, maximums, and standard deviations.
But imagine presenting a school principal with a report containing hundreds of numbers. It might be difficult to understand quickly.
What if you could turn those numbers into colourful charts and graphs? That is what data visualisation helps you achieve.
In this module, you will learn how to create charts in R and complete a simple data analysis project using a Nigerian business example.
Data visualisation is the process of presenting information using visual elements such as charts, graphs, and plots.
For example, a supermarket in Lagos can use charts to:
Visualisation makes it easier to identify patterns, trends, and differences in data.
There are different types of charts. Each one helps communicate a particular type of information.
A bar chart uses rectangular bars to compare values across different categories.
For example, a school can use a bar chart to compare the examination scores of students.
A line chart uses connected points to show how values change over time. A supermarket can use it to monitor sales from January to December.
A pie chart displays information as sections of a circle. It can show how different products contribute to total sales.
A histogram groups numerical values into ranges called bins. It helps you understand how values are distributed.
A scatter plot uses dots to show the relationship between two numerical variables. For example, you can use it to explore whether students who study for more hours tend to achieve higher examination scores.
R has a built-in plotting function called plot().
You can use it to create simple charts.
Let's create a basic chart using student examination scores.
scores <- c(65, 80, 75, 90, 55)
plot(scores)
R creates a basic plot showing the scores. Each point represents a student's score at its position in the dataset.
A bar chart is useful when comparing different categories. Let's create a chart showing the sales of products in a supermarket.
products <- c("Rice", "Beans", "Garri", "Oil", "Sugar")
sales <- c(40000, 25000, 18000, 30000, 15000)
barplot(
sales,
names.arg = products,
main = "Supermarket Product Sales",
xlab = "Products",
ylab = "Sales Amount",
col = "skyblue"
)
Let's understand the important parts:
barplot() creates the bar chart.sales contains the numerical values.names.arg displays the product names.main adds a chart title.xlab adds a label to the horizontal axis.ylab adds a label to the vertical axis.col changes the colour of the bars.A line chart helps you understand how values change over time. Let's imagine a supermarket wants to monitor its monthly sales.
months <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun")
monthly_sales <- c(50000, 65000, 60000, 80000, 75000, 95000)
plot(
monthly_sales,
type = "o",
xaxt = "n",
main = "Monthly Sales Performance",
xlab = "Month",
ylab = "Sales Amount",
col = "blue"
)
axis(1, at = 1:6, labels = months)
The argument type = "o" displays both points and connecting lines.
The axis() function allows us to display the month names on the horizontal axis.
The chart helps the business see when sales increased or decreased.
A pie chart is useful when you want to show how different categories contribute to a total.
Let's display the contribution of different products to supermarket sales.
products <- c("Rice", "Beans", "Garri", "Oil", "Sugar")
sales <- c(40000, 25000, 18000, 30000, 15000)
pie(
sales,
labels = products,
main = "Sales Contribution by Product",
col = rainbow(length(sales))
)
Each section of the pie chart represents a product's contribution to the total sales.
Pie charts work best when you have a small number of categories that add up to a meaningful total.
A histogram helps you understand how numerical values are distributed. For example, a teacher can use it to understand how examination scores are spread across different score ranges.
scores <- c(
45, 50, 55, 60, 65,
70, 72, 75, 80, 85,
88, 90, 92, 95, 98
)
hist(
scores,
main = "Distribution of Examination Scores",
xlab = "Examination Scores",
ylab = "Number of Students",
col = "lightgreen"
)
The histogram groups scores into intervals and shows how many values fall within each interval.
A scatter plot helps you explore the relationship between two numerical variables.
Imagine a teacher wants to know whether students who spend more time studying tend to achieve higher examination scores.
study_hours <- c(1, 2, 3, 4, 5, 6)
scores <- c(45, 50, 60, 70, 80, 90)
plot(
study_hours,
scores,
main = "Study Hours and Examination Scores",
xlab = "Study Hours",
ylab = "Examination Scores",
pch = 19,
col = "blue"
)
Each dot represents one student's study time and examination score. The chart can help you explore whether the two variables appear to be related.
Remember that a relationship between two variables does not automatically mean that one variable causes the other.
R has a popular visualisation package called ggplot2. It provides tools for creating professional-looking charts.
First, install and load the package:
install.packages("ggplot2")
library(ggplot2)
You only need to install the package once. Load it whenever you start a new R session and want to use it.
sales_data <- data.frame(
Product = c("Rice", "Beans", "Garri", "Oil", "Sugar"),
Sales = c(40000, 25000, 18000, 30000, 15000)
)
ggplot(sales_data, aes(x = Product, y = Sales)) +
geom_col(fill = "steelblue") +
labs(
title = "Supermarket Product Sales",
x = "Product",
y = "Sales Amount"
)
Here is what the code does:
ggplot() starts the chart.aes() identifies the information used on the chart axes.geom_col() creates bars using the supplied sales values.labs() adds the chart title and axis labels.monthly_data <- data.frame(
Month = c("Jan", "Feb", "Mar", "Apr", "May", "Jun"),
Sales = c(50000, 65000, 60000, 80000, 75000, 95000)
)
monthly_data$Month <- factor(
monthly_data$Month,
levels = c("Jan", "Feb", "Mar", "Apr", "May", "Jun")
)
ggplot(monthly_data, aes(x = Month, y = Sales, group = 1)) +
geom_line(color = "blue") +
geom_point(size = 3) +
labs(
title = "Monthly Sales Performance",
x = "Month",
y = "Sales Amount"
)
The geom_line() function creates the line, while
geom_point() displays the individual data points.
A good chart should have a clear title and meaningful labels. This helps people understand what the chart represents.
For example:
barplot(
sales,
names.arg = products,
main = "Monthly Product Sales in Lagos",
xlab = "Product Name",
ylab = "Sales in Naira",
col = "orange"
)
Always use titles and labels that clearly explain the information being presented.
After creating a chart, you may want to save it as an image for a report, presentation, or website.
You can save a chart as a PNG image using:
png("sales_chart.png", width = 800, height = 600)
barplot(
sales,
names.arg = products,
main = "Supermarket Sales",
xlab = "Products",
ylab = "Sales Amount",
col = "skyblue"
)
dev.off()
The png() function starts saving the chart to an image file.
The dev.off() function closes the graphics device and finishes saving the image.
You can find the saved image in your current working directory.
Use getwd() to check the folder location.
It is time to combine what you have learned throughout this course. Imagine a supermarket in Ibadan wants to understand its product sales.
The manager gives you the following sales information:
sales_data <- data.frame(
Product = c("Rice", "Beans", "Garri", "Oil", "Sugar", "Milk"),
Quantity = c(10, 8, 12, 6, 15, 9),
Price = c(8000, 4500, 3000, 6000, 2500, 5000)
)
print(sales_data)
Check the first records and understand the structure.
head(sales_data)
str(sales_data)
summary(sales_data)
Multiply the quantity sold by the price of each product.
sales_data$Total_Sales <-
sales_data$Quantity * sales_data$Price
print(sales_data)
total_revenue <- sum(sales_data$Total_Sales)
print(total_revenue)
average_sales <- mean(sales_data$Total_Sales)
print(average_sales)
best_product <- sales_data[
which.max(sales_data$Quantity),
]
print(best_product)
This identifies the product with the highest quantity sold. It does not necessarily identify the product that generated the most revenue.
barplot(
sales_data$Total_Sales,
names.arg = sales_data$Product,
main = "Total Sales by Product",
xlab = "Product",
ylab = "Sales in Naira",
col = "lightblue"
)
highest_revenue_product <- sales_data[
which.max(sales_data$Total_Sales),
]
print(highest_revenue_product)
After completing your analysis, explain what you discovered. Your report should include:
A school in Lagos wants to understand the performance of its students. Use R to analyse and visualise the following examination scores:
students <- data.frame(
Name = c("Ada", "Tunde", "Chika", "Emeka", "Bola", "David"),
Score = c(85, 72, 90, 65, 78, 95)
)
Complete these tasks:
Congratulations! You have completed the Introduction to R for Data Analysis course. Throughout the eight modules, you have learned important skills for working with data.
You have learned how to:
Learning R can help you develop skills that are useful in different data-related careers. Some career paths include:
Remember that learning R is a starting point. You should continue practising, working with real datasets, and developing other useful skills such as Excel, SQL, Python, and data visualisation.
Find a small dataset containing information about students, supermarket sales, business expenses, or another topic you understand.
Use R to complete a mini data analysis project:
Final lesson: A good data analyst does more than calculate numbers. A good analyst uses data to answer questions, explain findings, and support better decisions.
You have taken your first steps into R programming and data analysis. Keep practising, exploring datasets, and building projects. Every dataset you analyse is another opportunity to improve your skills.