Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Introduction to R for Data Analysis ยท Lesson 9 of 9

Module Eight

๐Ÿ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
9

Module 8: Data Visualisation and Practical Project with R

1. Introduction

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.

2. What Is Data Visualisation?

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:

  • Compare the sales of different products.
  • Identify the products with the highest sales.
  • Track sales performance over several months.
  • Understand changes in customer purchases.
  • Present business performance to management.

Visualisation makes it easier to identify patterns, trends, and differences in data.

3. Understanding Different Types of Charts

There are different types of charts. Each one helps communicate a particular type of information.

A. Bar Chart

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.

B. Line Chart

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.

C. Pie Chart

A pie chart displays information as sections of a circle. It can show how different products contribute to total sales.

D. Histogram

A histogram groups numerical values into ranges called bins. It helps you understand how values are distributed.

E. Scatter Plot

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.

4. Creating Your First Chart in R

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.

5. Creating a Bar Chart in R

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.

6. Creating a Line Chart in R

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.

7. Creating a Pie Chart in R

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.

8. Creating a Histogram in R

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.

9. Creating a Scatter Plot in R

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.

10. Using ggplot2 for Data Visualisation

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.

A. Creating a Bar Chart with ggplot2

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.

B. Creating a Line Chart with ggplot2

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.

11. Adding Titles and Labels to Charts

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.

12. Saving Charts from R

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.

13. Practical Project: Analysing Supermarket Sales

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)

Step 1: Explore the Dataset

Check the first records and understand the structure.

head(sales_data)

str(sales_data)

summary(sales_data)

Step 2: Calculate Total Sales for Each Product

Multiply the quantity sold by the price of each product.

sales_data$Total_Sales <-
  sales_data$Quantity * sales_data$Price

print(sales_data)

Step 3: Calculate Total Revenue

total_revenue <- sum(sales_data$Total_Sales)

print(total_revenue)

Step 4: Calculate Average Sales

average_sales <- mean(sales_data$Total_Sales)

print(average_sales)

Step 5: Find the Best-Selling Product by Quantity

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.

Step 6: Create a Sales Bar Chart

barplot(
  sales_data$Total_Sales,
  names.arg = sales_data$Product,
  main = "Total Sales by Product",
  xlab = "Product",
  ylab = "Sales in Naira",
  col = "lightblue"
)

Step 7: Identify the Product with the Highest Revenue

highest_revenue_product <- sales_data[
  which.max(sales_data$Total_Sales),
]

print(highest_revenue_product)

Step 8: Write a Short Business Report

After completing your analysis, explain what you discovered. Your report should include:

  • The total revenue generated by the supermarket.
  • The average revenue per product.
  • The product with the highest quantity sold.
  • The product that generated the highest revenue.
  • A chart showing the sales performance of each product.
  • One recommendation that could help the supermarket improve its sales.

14. Best Practices for Data Visualisation

  • Choose a chart that matches the information you want to explain.
  • Give every chart a clear and meaningful title.
  • Use labels that people can easily understand.
  • Avoid adding too many colours or unnecessary decorations.
  • Do not hide important information by changing chart scales misleadingly.
  • Make sure your charts represent the data accurately.
  • Explain the main finding instead of simply presenting a chart.
  • Check your calculations before sharing your report.

15. Practical Exercise

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:

  1. Display the dataset.
  2. Calculate the average examination score.
  3. Find the highest and lowest scores.
  4. Identify the student with the highest score.
  5. Create a bar chart comparing the students' scores.
  6. Create a histogram showing the distribution of scores.
  7. Write three sentences explaining what you discovered.

16. Final Course Summary

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:

  • Understand R programming and its uses in data analysis.
  • Install R and get started with RStudio.
  • Write basic R commands and create variables.
  • Work with vectors, lists, matrices, arrays, data frames, and factors.
  • Import CSV and Excel files into R.
  • Explore datasets using built-in R functions.
  • Clean missing values and remove duplicate records.
  • Transform data using R and the dplyr package.
  • Perform basic statistical analysis.
  • Create charts using base R and ggplot2.
  • Complete a simple data analysis project.

17. Career Opportunities After Learning R

Learning R can help you develop skills that are useful in different data-related careers. Some career paths include:

  • Data Analyst: Uses data to answer business questions and support decisions.
  • Business Analyst: Studies business information to identify problems and opportunities.
  • Statistician: Uses statistical methods to study information and explain findings.
  • Research Analyst: Collects and analyses information for research projects.
  • Data Scientist: Uses programming, statistics, and other techniques to discover patterns and build models.

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.

18. Final Challenge

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:

  1. Import or create your dataset.
  2. Explore the information.
  3. Clean any missing or incorrect values.
  4. Calculate useful statistics.
  5. Create at least two charts.
  6. Write a short report explaining your findings.

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.

Congratulations on Completing the Course!

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.

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (โ‚ฆ2,000 or 20,000 coins), and get a verified certificate with your name on it.

๐ŸŽ“ Sign Up to Get Certified
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
โ†’