Data Visualization

Author

Hassan Ghayas

Published

April 26, 2026

📦 Load Libraries

library(dplyr)

Attaching package: 'dplyr'
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
library(readxl)
library(ggplot2)

Simple Basic Graph

Basic graph types can be created in R, such as histograms, barplots, scatterplots or boxplots. These can be generated using commands or function such as hist(), barplot(), plot() or boxplot() respectively.

📂 Load dataset

# Read dataset
data_unique <- read_excel("cleaned_dummy_patient_data_R_workshop.xlsx")

Barplot

Prepare data for plot

# prepare data for plot
plot_data <- data_unique %>% 
  filter(test_procedure_name == "Hemoglobin") %>%
  group_by(sex) %>% 
  count(result_category)

Generate simple barplot

barplot(
  height = plot_data$n,
  names.arg = paste(plot_data$sex, plot_data$result_category, sep = "-"),
  col = "skyblue",
  main = "Hemoglobin Result by Gender",
  ylab = "Count",
  las = 2,
  cex.names = 0.6,
  cex.axis = 0.8
)

Grouped barplot

Prepare data for Grouped Bar Plot

plot_data2 <- table(
  data_unique$result_category[data_unique$test_procedure_name == "Hemoglobin"],
  data_unique$sex[data_unique$test_procedure_name == "Hemoglobin"]
)

Generate grouped bar plot

barplot(
  plot_data2,
  beside = TRUE,
  col = c("tomato", "skyblue", "lightgreen"),
  legend = TRUE,
  main = "Hemoglobin Result by Sex",
  xlab = "Sex",
  ylab = "Count",
  args.legend = list(x = "topright", inset = c(-0.05, -0.1))
)

Data visualization using ggplot2

This package is based on using the grammar of graphics concept. The grammar of graphics is implemented in a layered approach, using layers of information (data complemented with statistical or graphical information) to build up step by step to a final display of a graph.

ggplot2_layout

plotting using ggplot2

data_unique %>% 
  filter(test_procedure_name == "Hemoglobin") %>%
  ggplot()+
  geom_bar(aes(x=sex, fill =result_category), color = "black", position= 'dodge2')+
  xlab("Gender")+
  ylab("number of patient")+
  labs(
    title = "Hemoglobin",
    fill = 'Results'
  )+
  theme_bw()