User Tools

Site Tools


tutorials:r_plots

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
tutorials:r_plots [2026/09/18 17:56] – chkuotutorials:r_plots [2026/10/13 10:44] (current) – [Box plots] hychang
Line 4: Line 4:
  
 An user guide to walk through data visualization by box plot in R.\\ An user guide to walk through data visualization by box plot in R.\\
-Please download the tutorial and open with browser (like Chrome) for more detail.\\ +Please see the tutorials for more details.\\
- +
-[[https://drive.google.com/file/d/1g4NGAsX2VFJZ0xZkNwlBMMadp4LyTPHY/view?usp=drive_link|R Markdown Document for Boxplots]]\\+
  
  
 ==== One batch with replicates ==== ==== One batch with replicates ====
 +
 +=== Single batch boxplot tutorials ===
 +  * {{single-batch_boxplot_v01.pdf}}
 +
 === Sample input === === Sample input ===
   * {{sample1.xlsx}}   * {{sample1.xlsx}}
  
 === R script === === R script ===
-  * Please download the R script using the link below. 
-  * [[ https://drive.google.com/file/d/1AGVfmruh8ZEB9RTWmeKa-KBbS9-Zpp9x/view?usp=drive_link | single-batch_boxplot.R ]]\\ 
  
  
-<file> +<file r single-batch_boxplot.R> 
-rm(list=ls())+# Aim: This R script is about making single batch boxplot. 
 + 
 +# Data Description: One batch with replicates 
 +# - sample1.xlsx 
 +#   - Sheet1: Contains raw data across two columns: `Strain` and `Value`. Each strain includes 20 replicates. 
 +#   - Sheet2: Contains the statistical test result (Tukey's HSD). 
 +# 
 +# Output (both pdf and png format): 
 +# - Version 1: Displays all data points using a single color. 
 +# - Version 2: Colors the data points by strain and adds statistical significance group labels at the top. 
 +#--------------------------------------------------------------------------------------------------------------- 
 + 
 +### Step 0, Check packages 
 + 
 +# Required packages 
 +packages <- c("ggplot2", "readxl") 
 + 
 +# Check and install required packages 
 +for (pkg in packages) { 
 +  if (!requireNamespace(pkg, quietly = TRUE)) { 
 +    install.packages(pkg, repos = "https://cloud.r-project.org") 
 +  } 
 +} 
 + 
 +#--------------------------------------------------------------------------------------------------------------- 
 + 
 +### Step 1. Configuration 
 + 
 +## Set up a dedicated working directory to store your raw files and output plots.
  
 # working directory # working directory
-setwd("/home/hychang/R_pwd/2026-09-14_R-plots/Box_plots/")+working_path = "/scratch/hychang/R_wd/Rana001/Rana001.01/single-batch/"
  
-# load packages +# input data located directory 
-library(readxl) +input_path = "/scratch/hychang/R_wd/Rana001/Rana001.01/single-batch/"
-library(ggplot2)+
  
-### Step 1. import data, choose one of them to import file +# output folder for storing plots 
-# (1) fill in full path of your file and the sheet name +output_path = "/scratch/hychang/R_wd/Rana001/Rana001.01/single-batch/plots/"
-df1= read_xlsx("/home/hychang/R_pwd/2026-09-14_R-plots/Box_plots/sample1.xlsx", sheet = "Sheet1")+
  
-# (2) If you don't know the full path, use file.choose to select your file,  +## Set Input and output
-#     remember fill in the sheet name +
-df1= read_xlsx(file.choose(), sheet = "Sheet1")+
  
 +# File name of the raw data table, including the file extension
 +input_file_raw = "sample1.xlsx"
  
-### Step 2. import the multiple comparison result (optional)+# Worksheet name of the raw data table 
 +input_sheet_raw =  "Sheet1"
  
-df2= read_xlsx("/home/hychang/R_pwd/2026-09-14_R-plots/Box_plots/sample1.xlsx", sheet = "Sheet2")+# (Optional) File name of the statistical test result table, including the file extension 
 +input_file_stat = "sample1.xlsx"
  
 +# (Optional) Worksheet name of the statistical test result table
 +input_sheet_stat = "Sheet2"
  
-### Step 3. Inspect data+# Column names in the input data 
 +x_column = "Strain" 
 +y_column = "Value"
  
-# dimension +# Column name of statistical significance group letters, skip if the statistical test not available 
-df1; dim(df1) +stat_column = "groups"
-df2; dim(df2)+
  
-# counts of strain +# Output file names of the figures, including the file extension 
-table(df1$"Strain") +output_file_1 = "single-batch_v1.pdf" 
-table(df1$"Strain", useNA = "always")+output_file_2 = "single-batch_v2.pdf" 
 +output_file_3 = "single-batch_v1.png" 
 +output_file_4 = "single-batch_v2.png"
  
-# range of value +# Set up a dedicated working directory to store your raw files and output plots. 
-range(df1$"Value")+dir.create(working_path, recursive = TRUE, showWarnings = FALSE) 
 +dir.create(input_path, recursive = TRUE, showWarnings = FALSE) 
 +dir.create(output_path, recursive = TRUE, showWarnings = FALSE)
  
 +## Setting figure parameters
  
-### Step 4. setting sample order+# the names of x and y axis 
 +x_lab = "Strain" 
 +y_lab = "Value"
  
-# set your ordering in levels +# y axis range and breaks 
-df1$"Strain" = factor(df1$"Strain", +y_range = c(0, 7) 
-                      levels = c("A", "B", "C"))+y_breaks = c(0, 2, 4, 6)
  
 +# font size of x and y axis title (axis label)
 +axis_title_size = 16
  
-### Step 5. plot+# font size of x and y axis text (tick label) 
 +axis_text_size = 14
  
-# version 1+# sample ordering 
 +x_order = c("A", "B", "C") 
 + 
 +# size of data points 
 +point_size= 2 
 + 
 +# box size 
 +box_size= 0.4 
 + 
 +# use a single color for all data points 
 +color_single = c("#003175") 
 + 
 +# use multiple colors for the data points; the number of colors should match the number of samples 
 +color_multiple = c(c("#1B9E77", "#D95F02", "#7570B3")) 
 + 
 +## Export setting 
 +pdf_width = 6 
 +pdf_height = 4 
 +png_width = 600 
 +png_height = 400 
 + 
 +#--------------------------------------------------------------------------------------------------------------- 
 + 
 +### Step 2. Setup and Import data 
 + 
 +# Set working directory 
 +setwd(working_path) 
 + 
 +# load packages 
 +library(readxl) 
 +library(ggplot2) 
 + 
 +# Import raw data 
 +df1= read_xlsx(file.path(input_path, input_file_raw), sheet = input_sheet_raw) 
 + 
 +# (Optional) Import statistical test result. Skip this step if you don't have the results. 
 +df2= read_xlsx(file.path(input_path, input_file_stat), sheet = input_sheet_stat) 
 + 
 +# Sample ordering 
 +df1[[x_column]] = factor(df1[[x_column]], levels = x_order) 
 +df2[[x_column]] = factor(df2[[x_column]], levels = x_order) # skip this if df2 not available 
 + 
 +# Display the data frame and view its dimensions (number of rows and columns). 
 +df1; dim(df1) 
 +df2; dim(df2) # skip this if df2 not available 
 + 
 +# show sample counts and if there is NA value. 
 +table(df1[[x_column]], useNA = "always") 
 + 
 +# range of value 
 +range(df1[[y_column]]) 
 +#--------------------------------------------------------------------------------------------------------------- 
 + 
 +#### Step 3. Generate Plots 
 + 
 +# Version 1
 # all data points using a single, uniform color. # all data points using a single, uniform color.
-p1= ggplot(data = df1, aes(x= Strain, y= Value))+ +p1 = ggplot(data = df1, aes(x = .data[[x_column]], y = .data[[y_column]])) + 
-  geom_boxplot(width = 0.4, outlier.shape = NA)+ +  geom_boxplot(width = box_size, 
-  geom_point(color= "#003175", size= 2, +               outlier.shape = NA) + 
-             position = position_jitter(width = 0.2,height = 0))+ +  geom_point(color = color_single, 
-  scale_y_continuous(limits = c(0, NA))+ +             size = point_size, 
-  labs(x= "Strain", y= "Value")+ +             position = position_jitter(width = 0.2, height = 0)) + 
-  theme_classic()+ +  scale_y_continuous(limits = y_range, 
-  theme(axis.title = element_text(size = 16), +                     breaks = y_breaks) + 
-        axis.text = element_text(size = 14))+  labs(x = x_lab, 
 +       y = y_lab) + 
 +  theme_classic() + 
 +  theme(axis.title = element_text(size = axis_title_size), 
 +        axis.text = element_text(size = axis_text_size))
  
 # show plot # show plot
Line 81: Line 181:
  
  
-# version 2 +# Version 2 
-# Colors data points by Strain and adds statistical significance group labels at the top. +# colors data points by Strain and adds statistical significance group labels at the top. 
-p2= ggplot(data = df1, aes(x= Strain, y= Value))+ +p2 = ggplot(data = df1, aes(x = .data[[x_column]], y = .data[[y_column]])) + 
-  geom_boxplot(width = 0.4, outlier.shape = NA)+ +  geom_boxplot(width = box_size, outlier.shape = NA) + 
-  geom_point(aes(color= Strain), size = 2, +  geom_point(aes(color = .data[[x_column]]), 
-             position = position_jitter(width = 0.2,height = 0))+ +             size = point_size, 
-  geom_text(data = df2, aes(x= Strain, y= Inf, label = groups), vjust= "inward")+ +             position = position_jitter(width = 0.2, height = 0)) + 
-  scale_color_manual(values = c("#1B9E77", "#D95F02", "#7570B3"))+ +  geom_text(data = df2, 
-  scale_y_continuous(limits = c(0, NA))+ +            aes(x = .data[[x_column]], y = Inf, label = .data[[stat_column]]), 
-  labs(x= "Strain", y= "Value")+ +            vjust = "inward") + 
-  theme_classic()+ +  scale_color_manual(values = c(color_multiple)) + 
-  theme(axis.title = element_text(size = 16), +  scale_y_continuous(limits = y_range, 
-        axis.text = element_text(size = 14))+                     breaks = y_breaks) + 
 +  labs(x = x_lab, 
 +       y = y_lab) + 
 +  theme_classic() + 
 +  theme(axis.title = element_text(size = axis_title_size), 
 +        axis.text = element_text(size = axis_text_size))
  
 # show plot # show plot
Line 99: Line 204:
  
  
-### Step 6. Export+#--------------------------------------------------------------------------------------------------------------- 
 +#### Step 4. Export Plots 
 + 
 +## Export PDF
  
 # version 1 PDF export # version 1 PDF export
-pdf("simple_boxplot1.pdf")+pdf(file.path(output_path, output_file_1), width = pdf_width, height = pdf_height)
 p1 p1
 dev.off() dev.off()
  
 # version 2 PDF export # version 2 PDF export
-pdf("/home/hychang/R_pwd/2026-09-14_R-plots/Box_plots/simple_boxplot2.pdf")+pdf(file.path(output_path, output_file_2), width = pdf_width, height = pdf_height)
 p2 p2
 dev.off() dev.off()
  
-# change the width and height to 6 and 4 in inch 
-pdf("simple_boxplot1_w6h4.pdf", width = 6, height = 4) 
-p1 
-dev.off() 
  
-pdf("simple_boxplot2_w6h4.pdf", width = 6, height = 4) 
-p2 
-dev.off() 
  
 +## Export PNG
  
-# version 1 PNG export +# Version 1 PNG export 
-png("simple_boxplot1.png")+png(file.path(output_path, output_file_3), width = png_width, height = png_height)
 p1 p1
 dev.off() dev.off()
  
-# version 2 PNG export +# Version 2 PNG export 
-png("simple_boxplot2.png")+png(file.path(output_path, output_file_4), width = png_width, height = png_height)
 p2 p2
 dev.off() dev.off()
  
-# change width and height to 600 and 400 in pixels 
-png("simple_boxplot1_w600h400.png", width = 600, height = 400) 
-p1 
-dev.off() 
  
-png("simple_boxplot2_w600h400.png", width = 600, height = 400) +### END this script 
-p2 +
-dev.off()+
  
 </file> </file>
Line 148: Line 245:
   * **Version 1**: Displays all data points using a single, uniform color.   * **Version 1**: Displays all data points using a single, uniform color.
     * PNG: setting width 600 and height 400.     * PNG: setting width 600 and height 400.
-    * {{ simple_boxplot1_w600h400.png }} +    * {{ single-batch_v1.png }} 
-    * PDF: width 6 inch and height 4 inch. {{ simple_boxplot1_w6h4.pdf }}+    * PDF: width 6 inch and height 4 inch. {{ single-batch_v1.pdf }}
   * **Version 2**: Colors data points by Strain and adds statistical significance group labels at the top.   * **Version 2**: Colors data points by Strain and adds statistical significance group labels at the top.
     * PNG: setting width 600 and height 400.     * PNG: setting width 600 and height 400.
-    * {{ simple_boxplot2_w600h400.png }} +    * {{ single-batch_v2.png }} 
-    * PDF: width 6 inch and height 4 inch. {{ simple_boxplot2_w6h4.pdf }}+    * PDF: width 6 inch and height 4 inch. {{ single-batch_v2.pdf }}
 \\ \\
  
 ==== Multiple batches with replicates ==== ==== Multiple batches with replicates ====
 +
 +=== Multiple batches boxplot tutorials ===
 +  * {{multiple-batches_boxplot_v01.pdf}}
 +
 === Sample input === === Sample input ===
   * {{sample2.xlsx}}   * {{sample2.xlsx}}
 +
 === R script === === R script ===
-  * Please download the R script using the link below. + 
-  * [[ https://drive.google.com/file/d/1XbvymKhrPuArYFD4bu3JaP2r2bGRtTas/view?usp=drive_link | mutiple-batches_boxplot.R ]]+ 
 +<file r multiple-batches_boxplot.R> 
 + 
 +# Aim: This R script is about generating multiple batches boxplot. 
 + 
 +# Data Description: Multiple batches with replicates 
 +# - sample1.xlsx 
 +#   - Sheet1: Contains raw data across three columns: `Strain`, `Batch`, `Value`. Each strain has three batches. 
 +#   - Sheet2: Contains the statistical test result (Tukey's HSD). 
 +# 
 +# Output (both pdf and png format): 
 +# - Version 1: Displays data with batches shown in distinct colors. 
 +# - Version 2: Displays batches in distinct colors and adds statistical significance group labels at the top. 
 +#--------------------------------------------------------------------------------------------------------------- 
 + 
 +### Step 0, Check packages 
 + 
 +# Required packages 
 +packages <- c("ggplot2", "readxl") 
 + 
 +# Check and install required packages 
 +for (pkg in packages) { 
 +  if (!requireNamespace(pkg, quietly = TRUE)) { 
 +    install.packages(pkg, repos = "https://cloud.r-project.org") 
 +  } 
 +} 
 + 
 +#--------------------------------------------------------------------------------------------------------------- 
 + 
 +### Step 1. Configuration 
 + 
 +## Set up a dedicated working directory to store your raw files and output plots. 
 + 
 +# working directory 
 +working_path = "/scratch/hychang/R_wd/Rana001/Rana001.01/multiple-batches/" 
 + 
 +# input data located directory 
 +input_path = "/scratch/hychang/R_wd/Rana001/Rana001.01/multiple-batches/" 
 + 
 +# output folder for storing plots 
 +output_path = "/scratch/hychang/R_wd/Rana001/Rana001.01/multiple-batches/plots/" 
 + 
 +## Set Input and output 
 + 
 +# File name of the raw data table, including the file extension 
 +input_file_raw = "sample2.xlsx" 
 + 
 +# Worksheet name of the raw data table 
 +input_sheet_raw = "Sheet1" 
 + 
 +# File name of the statistical test result table, including the file extension 
 +input_file_stat = "sample2.xlsx" 
 + 
 +# Worksheet name of the statistical test result table 
 +input_sheet_stat = "Sheet2" 
 + 
 +# Column names in the input data 
 +x_column = "Strain" 
 +y_column = "Value" 
 +batch_column = "Batch" 
 + 
 +# Column name of statistical significance group letters,  
 +# skip if the statistical test not available 
 +stat_column = "groups"   
 + 
 +# Output file names of the figures, including the file extension 
 +output_file_1 = "mult-batches_v01.pdf" 
 +output_file_2 = "mult-batches_v02.pdf" 
 +output_file_3 = "mult-batches_v01.png" 
 +output_file_4 = "mult-batches_v02.png" 
 + 
 +# Set up a dedicated working directory to store your raw files and output plots. 
 +dir.create(working_path, recursive = TRUE, showWarnings = FALSE) 
 +dir.create(input_path, recursive = TRUE, showWarnings = FALSE) 
 +dir.create(output_path, recursive = TRUE, showWarnings = FALSE) 
 + 
 +## Setting figure parameters 
 + 
 +# the names of x and y axis 
 +x_lab = "Strain" 
 +y_lab = "Value" 
 + 
 +# y axis range and breaks 
 +y_range = c(0, 6) 
 +y_breaks = c(0, 2, 4, 6) 
 + 
 +# font size of x and y axis title (axis label) 
 +axis_title_size = 16 
 + 
 +# font size of x and y axis text (tick label) 
 +axis_text_size = 14 
 + 
 +# sample ordering 
 +x_order = c("A", "B", "C") 
 + 
 +# size of data points 
 +point_size= 2 
 + 
 +# box size 
 +box_size= 0.4 
 + 
 +# space between batches (points) 
 +space_batch = 0.3 
 + 
 +# use multiple colors for the data points;  
 +# the number of colors should match the number of batches 
 +color_multiple = c(c("#1B9E77", "#D95F02", "#7570B3")) 
 + 
 +## Export setting 
 +pdf_width = 6 
 +pdf_height = 4 
 +png_width = 600 
 +png_height = 400 
 + 
 +#--------------------------------------------------------------------------------------------------------------- 
 + 
 +### Step 2. Setup and Import data 
 + 
 +# Set working directory 
 +setwd(working_path) 
 + 
 +# load packages 
 +library(readxl) 
 +library(ggplot2) 
 + 
 +# Import raw data 
 +df1= read_xlsx(file.path(input_path, input_file_raw), sheet = input_sheet_raw) 
 + 
 +# (Optional) Import statistical test result. Skip this step if you don't have the results. 
 +df2= read_xlsx(file.path(input_path, input_file_stat), sheet = input_sheet_stat) 
 + 
 +# Sample ordering 
 +df1[[x_column]] = factor(df1[[x_column]], levels = x_order) 
 +df2[[x_column]] = factor(df2[[x_column]], levels = x_order) # skip this if df2 not available 
 + 
 +# Display the data frame and view its dimensions (number of rows and columns). 
 +df1; dim(df1) 
 +df2; dim(df2) # skip this if df2 not available 
 + 
 +# Show sample counts, including NA values 
 +table(df1[[x_column]], useNA = "always") 
 + 
 +# Show the range of values 
 +range(df1[[y_column]]) 
 + 
 +# check batch counts, including NA values 
 +table(df1[[batch_column]], useNA = "always") 
 +#--------------------------------------------------------------------------------------------------------------- 
 + 
 +#### Step 3. Generate Plots 
 + 
 +# Version 1 
 +# all data points using a single, uniform color. 
 +p1= ggplot(data= df1, aes(x= .data[[x_column]], y= .data[[y_column]]))+ 
 +  geom_boxplot(width = box_size,  
 +               outlier.shape = NA)+ 
 +  geom_point(data= df1,  
 +             aes(fill= .data[[batch_column]]), 
 +             shape = 21, 
 +             size = point_size, 
 +             position= position_dodge(width = space_batch))+ 
 +  scale_fill_manual(values = color_multiple)+ 
 +  scale_y_continuous(limits = y_range, 
 +                     breaks = y_breaks)+ 
 +  labs(x= x_lab, y= y_lab)+  
 +  theme_classic()+ 
 +  theme(axis.title = element_text(size = axis_title_size), 
 +        axis.text = element_text(size = axis_text_size)) 
 + 
 +# show plot 
 +p1 
 + 
 + 
 +# Version 2 
 +# colors data points by Strain and adds statistical significance group labels at the top. 
 +p2= ggplot(data = df1, aes(x= .data[[x_column]], y= .data[[y_column]]))+ 
 +  geom_boxplot(width = box_size, outlier.shape = NA)+ 
 +  geom_point(aes(fill= .data[[batch_column]]), 
 +             shape = 21,  
 +             size = point_size, 
 +             position= position_dodge(width = space_batch))+ 
 +  geom_text(data = df2,  
 +            aes(x= .data[[x_column]], y= Inf, label = .data[[stat_column]]),  
 +            vjust= "inward")+ 
 +  scale_fill_manual(values = color_multiple)+ 
 +  scale_y_continuous(limits = y_range, 
 +                     breaks = y_breaks)+ 
 +  labs(x= x_lab, y= y_lab)+  
 +  theme_classic()+ 
 +  theme(axis.title = element_text(size = axis_title_size), 
 +        axis.text = element_text(size = axis_text_size)) 
 + 
 +# show plot 
 +p2 
 + 
 + 
 +#--------------------------------------------------------------------------------------------------------------- 
 +#### Step 4. Export Plots 
 + 
 +## Export PDF 
 + 
 +# version 1 PDF export 
 +pdf(file.path(output_path, output_file_1), width = pdf_width, height = pdf_height) 
 +p1 
 +dev.off() 
 + 
 +# version 2 PDF export 
 +pdf(file.path(output_path, output_file_2), width = pdf_width, height = pdf_height) 
 +p2 
 +dev.off() 
 + 
 + 
 + 
 +## Export PNG 
 + 
 +# Version 1 PNG export 
 +png(file.path(output_path, output_file_3), width = png_width, height = png_height) 
 +p1 
 +dev.off() 
 + 
 +# Version 2 PNG export 
 +png(file.path(output_path, output_file_4), width = png_width, height = png_height) 
 +p2 
 +dev.off() 
 + 
 + 
 +### END this script 
 + 
 +</file> 
  
 === Sample output === === Sample output ===
Line 168: Line 499:
   * **Version 1**: Displays data with batches shown in distinct colors.   * **Version 1**: Displays data with batches shown in distinct colors.
     * PNG: setting width 600 and height 400.     * PNG: setting width 600 and height 400.
-    * {{ mult_boxplot1_w600h400.png }} +    * {{ mult-batches_v01.png }} 
-    * PDF: width 6 inch and height 4 inch. {{ mult_boxplot1_w6h4.pdf }}+    * PDF: width 6 inch and height 4 inch. {{ mult-batches_v01.pdf }}
   * **Version 2**: Displays batches in distinct colors and adds statistical significance group labels at the top.   * **Version 2**: Displays batches in distinct colors and adds statistical significance group labels at the top.
     * PNG: setting width 600 and height 400.     * PNG: setting width 600 and height 400.
-    * {{ mult_boxplot2_w600h400.png }} +    * {{ mult-batches_v02.png }} 
-    * PDF: width 6 inch and height 4 inch. {{ mult_boxplot2_w6h4.pdf }}+    * PDF: width 6 inch and height 4 inch. {{ mult-batches_v02.pdf }}
  
tutorials/r_plots.1789725408.txt.gz · Last modified: by chkuo