-
Notifications
You must be signed in to change notification settings - Fork 1
/
RSW_CPTR6_analysis_markdown.Rmd
2078 lines (1456 loc) · 64.6 KB
/
RSW_CPTR6_analysis_markdown.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Annunziata DSP Analysis for Protein Panel"
output: html_document
date: "2024-02-13"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_knit$set(root.dir = '/rstudio-files/ccr-dceg-data/users/ned/DSPWorkflow')
# Increase the time out for downloading the DSP package
options(timeout = max(300, getOption("timeout")))
```
## Load the Input Data
``` {r Load Data, echo=TRUE}
# Create a folder to hold the test data.
# Below we have designated the folder 'test_data'
# Set paths for downloading dcc files
#downloads.path <- "test_data/Human_Kidney/downloaded/"
#tar.file.name <- "kidney_dccs.tar.gz"
#full.tar.path <- paste0(downloads.path,tar.file.name)
# Check if dcc files were previously downloaded
#if (!file.exists(full.tar.path)) {
# Download dcc files and place in data folder
# data.url <- "http://hpc.nih.gov/~CCBR/DSPWorkflow/kidney_dccs.tar.gz"
# download.file(data.url, full.tar.path)
# untar(full.tar.path, exdir = downloads.path)
#}
library(readxl)
project.folder.path <- "/rstudio-files/ccr-dceg-data/users/ned/CPTR/CPTR-6 Annunziata/"
dcc.files <- dir(
file.path(paste0(project.folder.path, "dccs")),
pattern = ".dcc$",
full.names = TRUE,
recursive = TRUE
)
pkc.files <- c(paste0(project.folder.path, "Mm_P_NGS_Core_v1.0.pkc"),
paste0(project.folder.path, "Mm_P_NGS_ImmuneActivation_v1.0.pkc"),
paste0(project.folder.path, "Mm_P_NGS_ImmuneCellTyping_v1.0.pkc"),
paste0(project.folder.path, "Mm_P_NGS_Myeloid_v1.0.pkc"))
annotation.file.path <- paste0(project.folder.path, "CPTR6_Annunziata_annotation.xlsx")
annotation.df <- read_excel("/rstudio-files/ccr-dceg-data/users/ned/CPTR/CPTR-6 Annunziata/CPTR_6_DSP_Annunziata/CPTR6_Annunziata_annotation.xlsx")
```
# Set up the GeoMx Set object
```{r Study Design, echo=TRUE}
library(GeomxTools)
# Establish the names of important annotation columns
slide.name.col <- "slide name"
group.col <- "age"
subgroup.col <- "treatment"
segment.col <- "segment"
area.col <- "area"
nuclei.col <- "nuclei"
# Load all of the input DCC files, annotation, and PKC files
object <-
readNanoStringGeoMxSet(
dccFiles = dcc.files,
pkcFiles = pkc.files,
phenoDataFile = annotation.file.path,
phenoDataSheet = "Annotation template",
phenoDataDccColName = "Sample_ID",
protocolDataColNames = c("aoi", "roi"),
experimentDataColNames = c("panel"),
analyte = "protein")
# Print out a summary of the object
print(object)
# Rename all of the required columns based on user parameters in data
colnames(object@phenoData@data)[colnames(object@phenoData@data) == slide.name.col] = "slide_name"
# Rename all of the required columns based on user parameters in metadata
rownames(object@phenoData@varMetadata)[rownames(object@phenoData@varMetadata) == slide.name.col] = "slide_name"
# Establish the segment specific IDs
segment.id.length <- 4
pData(object)$segmentID <- paste0(substr(pData(object)[[group.col]], 1, segment.id.length),
"|",
substr(pData(object)[[subgroup.col]], 1, segment.id.length),
"|",
substr(pData(object)$segment, 1, segment.id.length),
"|",
substr(pData(object)$slide_name, 1, segment.id.length),
"|",
sData(object)$roi)
```
# Sankey Plot
```{r}
library(ggplot2)
library(ggforce)
# Define the lanes of the Sankey plot
lane1 <- "treatment"
lane2 <- "age"
lane3 <- "segment"
lane4 <- "slide_name"
fill_lane <- "treatment"
#Establish variables for the Sankey plot
x <- id <- y <- n <- NULL
# select the annotations we want to show, use `` to surround column
# names with spaces or special symbols
# Create a count matrix
count.mat <- count(pData(object),
!!as.name(lane1),
!!as.name(lane2),
!!as.name(lane3),
!!as.name(lane4))
# Remove any rows with NA values
na.per.column <- colSums(is.na(count.mat))
na.total.count <- sum(na.per.column)
if(na.total.count > 0){
count.mat <- count.mat[!rowSums(is.na(count.mat)),]
rownames(count.mat) <- 1:nrow(count.mat)
}
# Gather the data and plot in order: lane 1, lane 2, ..., lane n
# gather_set_data creates x, id, y, and n fields within sankey.count.data
# Establish the levels of the Sankey
sankey.count.data <- gather_set_data(count.mat, 1:4)
sankey.count.data$x <-
factor(
sankey.count.data$x,
levels = c(as.name(lane1), as.name(lane2), as.name(lane3), as.name(lane4))
)
# For position of Sankey 100 segment scale
adjust.scale.pos = 0
# plot Sankey diagram
sankey.plot <-
ggplot(sankey.count.data,
aes(
x,
id = id,
split = y,
value = n
)) +
geom_parallel_sets(aes(fill = !!as.name(fill_lane)), alpha = 0.5, axis.width = 0.1) +
geom_parallel_sets_axes(axis.width = 0.2) +
geom_parallel_sets_labels(color = "gray",
size = 5,
angle = 0) +
theme_classic(base_size = 14) +
theme(
legend.position = "bottom",
axis.ticks.y = element_blank(),
axis.line = element_blank(),
axis.text.y = element_blank()
) +
scale_y_continuous(expand = expansion(0)) +
scale_x_discrete(expand = expansion(0)) +
labs(x = "", y = "") +
annotate(
geom = "segment",
x = (4.25 - adjust.scale.pos),
xend = (4.25 - adjust.scale.pos),
y = 20,
yend = 120,
lwd = 2
) +
annotate(
geom = "text",
x = (4.19 - adjust.scale.pos),
y = 70,
angle = 90,
size = 5,
hjust = 0.5,
label = "100 segments"
)
print(sankey.plot)
```
## 2. QC Preprocessing:
```{r QC Preprocessing, echo=TRUE}
library(GeomxTools)
library(tibble)
library(dplyr)
results.folder <- "/rstudio-files/ccr-dceg-data/users/ned/CPTR/CPTR-6 Annunziata/results/"
# Set the QC flags using the Nanostring defaults
qc.output <- setSegmentQCFlags(object,
qcCutoffs = list(
minSegmenReads = 1000,
percentAligned = 80,
percentTrimmed = 80,
percentStitched = 80,
percentSaturation = 50,
minNegativeCount = 10,
maxNTCCount = 60,
minArea = 16000))
# Review QC table low sequenced AOIs
qc <- protocolData(qc.output)
qc.df <- qc@data
print(qc.df)
# Review control probes
hk.names <- hkNames(qc.output)
print(hk.names)
igg.names <- iggNames(qc.output)
igg.names
fig <- qcProteinSignal(object = qc.output, neg.names = igg.names)
proteinOrder <- qcProteinSignalNames(object = qc.output, neg.names = igg.names)
fig()
# Save the feature plot
feature.plot <- fig()
export.feature.plot <- FALSE
if(export.feature.plot == TRUE){
ggsave(file.path(paste0(results.folder, "feature_plot.png")), plot = feature.plot, width = 12, height = 10)
}
# Generate a list of flagged segments
## Annotation columns
object <- qc.output
annotation.data <- pData(object)
## Annotation column names
annotation.column.names <- colnames(annotation.data)
## Start the list of selected annotation columns
select.annotation.columns <- "segmentID"
## Check if area and nuclei are included
if("area" %in% annotation.column.names){
select.annotation.columns <- c("area", select.annotation.columns)
}
if("nuclei" %in% annotation.column.names){
select.annotation.columns <- c("nuclei", select.annotation.columns)
}
## The annotation names based on selected columns as a df
## drop = FALSE ensures single column is still a df
select.annotation.data <- annotation.data[, select.annotation.columns,
drop = FALSE]
select.annotation.data <- rownames_to_column(select.annotation.data,
var = "SampleID")
# Gather the QC flagged rows
## Gather the qc data
segment.qc.data <- object@protocolData@data
## The nested flag dataframe
flag.columns <- segment.qc.data %>% select(starts_with("QCFlags"))
## Rows with a positive flag
flagged.rows <- flag.columns[rowSums(flag.columns$QCFlags == TRUE) > 0, ]
flagged.rows <- as.data.frame(flagged.rows)
flagged.rows <- rownames_to_column(flagged.rows, var = "SampleID")
# Gather the additional QC data
## Additional QC column names
add.qc.column.names <- c("Raw",
"Trimmed (%)",
"Stitched (%)",
"Aligned (%)",
"Saturated (%)")
## Check for NTC column
if("NTC" %in% colnames(segment.qc.data)){
add.qc.column.names <- c("NTC", add.qc.column.names)
}
## Additional QC data
add.qc.columns <- segment.qc.data[, add.qc.column.names]
add.qc.columns <- rownames_to_column(add.qc.columns, var = "SampleID")
## Convert single column matrix and dataframes into vectors
## May cause an issue if there is more then one PKC file
matrix.column <- add.qc.columns$NegGeoMean
vector.column <- as.vector(matrix.column)
add.qc.columns$NegGeoMean <- vector.column
add.qc.columns$TrimmedPerc <- sapply(add.qc.columns$`Trimmed (%)`,
function(x) unname(unlist(x)))
add.qc.columns$TrimmedPerc <- as.vector(add.qc.columns$TrimmedPerc[,1])
add.qc.columns$StitchedPerc <- sapply(add.qc.columns$`Stitched (%)`,
function(x) unname(unlist(x)))
add.qc.columns$StitchedPerc <- as.vector(add.qc.columns$StitchedPerc[,1])
add.qc.columns$AlignedPerc <- sapply(add.qc.columns$`Aligned (%)`,
function(x) unname(unlist(x)))
add.qc.columns$AlignedPerc <- as.vector(add.qc.columns$AlignedPerc[,1])
add.qc.columns$SaturatedPerc <- sapply(add.qc.columns$`Saturated (%)`,
function(x) unname(unlist(x)))
add.qc.columns$SaturatedPerc <- as.vector(add.qc.columns$SaturatedPerc[,1])
## Remove the nested data frames
add.qc.columns <- add.qc.columns[, -which(names(add.qc.columns) == "Trimmed (%)")]
add.qc.columns <- add.qc.columns[, -which(names(add.qc.columns) == "Stitched (%)")]
add.qc.columns <- add.qc.columns[, -which(names(add.qc.columns) == "Aligned (%)")]
add.qc.columns <- add.qc.columns[, -which(names(add.qc.columns) == "Saturated (%)")]
# Create the final QC flag data frame with all additional info
## Merge the annotation, flag, and additional qc data frames
merge.qc.flagged.df <- merge(merge(select.annotation.data, add.qc.columns,
by = "SampleID"),
flagged.rows, by = "SampleID")
## Reorder columns so that info is next to flag
final.column.order <- c("SampleID",
"segmentID",
"Raw",
"LowReads",
"TrimmedPerc",
"LowTrimmed",
"StitchedPerc",
"LowStitched",
"AlignedPerc",
"LowAligned",
"SaturatedPerc",
"LowSaturation")
## Add NTC, area, and/or nuclei if part of annotation
if("NTC" %in% colnames(segment.qc.data)){
final.column.order <- c(final.column.order, "NTC", "HighNTC")
}
if("area" %in% annotation.column.names){
final.column.order <- c(final.column.order, "area", "LowArea")
}
if("nuclei" %in% annotation.column.names){
final.column.order <- c(final.column.order, "nuclei", "LowNuclei")
}
## The final QC flag df
final.flagged.segment.df <- merge.qc.flagged.df[, final.column.order]
## Final renaming of columns
colnames(final.flagged.segment.df)[colnames(final.flagged.segment.df) == "Raw"] <- "RawReadCount"
print(final.flagged.segment.df)
qc.folder <- paste0(project.folder.path, "qc/")
export.qc.flag.summary <- FALSE
if(export.qc.flag.summary == TRUE){
write.csv(qc.df, file = paste0(qc.folder, "CPTR6_QC_flag_summary.csv"))
}
```
## 3. Filtering:
```{r Filtering, echo=TRUE}
# Can remove segments based on flags
# Below is how you would remove segments flagged with low saturation
# low sequenced ROIs
lowSaturation <- which(as.data.frame(protocolData(qc.output)[["QCFlags"]])["LowSaturation"] == TRUE)
# remove low quality ROIs and compare the before and after
#passedQC <- qc.output[, -lowSaturation]
#dim(qc.output)
#dim(passedQC)
```
## 4. Normalization:
```{r Normalization, echo=TRUE}
# Check for best normalization type
norm.factors <- computeNormalizationFactors(qc.output,
igg.names = igg.names,
hk.names = hk.names,
area = "area",
nuclei = "Nuclei count")
# Concordance plots for Negative Controls
igg.concordance.treatment <- plotConcordance(object = qc.output,
targetList = igg.names,
plotFactor = "age")
igg.concordance.age <- plotConcordance(object = qc.output,
targetList = igg.names,
plotFactor = "treatment")
print(igg.concordance.treatment)
print(igg.concordance.age)
# Concordance plots for Housekeeping controls
hk.concordance.treatment <- plotConcordance(object = qc.output,
targetList = hk.names,
plotFactor = "age")
hk.concordance.age <- plotConcordance(object = qc.output,
targetList = hk.names,
plotFactor = "treatment")
print(hk.concordance.treatment)
print(hk.concordance.age)
# Generate normalized counts for each normalization type
norm.hk <- normalize(qc.output, norm_method="hk", toElt = "hk_norm")
norm.neg <- normalize(qc.output, norm_method="neg", toElt = "neg_norm")
norm.q3 <- normalize(qc.output, norm_method="quant", desiredQuantile = .75, toElt = "q_norm")
# Generate probe figure for negative normalized counts
probe.signal.hk <- qcProteinSignal(object = norm.neg, neg.names = hk.names)
probe.signal.neg <- qcProteinSignal(object = norm.neg, neg.names = igg.names)
proteinOrder <- qcProteinSignalNames(object = norm.neg, neg.names = igg.names)
fig()
# Export all read count for raw and normalization methods
## raw
raw_counts <- as.data.frame(norm.hk@assayData$exprs)
feature_list <- rownames(raw_counts)
raw_counts <- cbind("feature" = feature_list, raw_counts)
# log counts
raw_log_counts <- raw_counts %>% mutate(across(starts_with("DSP"),~log2(. + 1)))
## Housekeeping Normalization
hk.norm_counts <- norm.hk@assayData$hk_norm
feature_list <- rownames(hk.norm_counts)
hk.norm_counts <- cbind("feature" = feature_list, hk.norm_counts)
# log counts
hk_log_counts <- as.data.frame(hk.norm_counts) %>% mutate(across(starts_with("DSP"),~ceiling(as.numeric(.x)))) %>% mutate(across(starts_with("DSP"),~log2(. + 1)))
## Negative Normalization
neg.norm_counts <- norm.neg@assayData$neg_norm
feature_list <- rownames(neg.norm_counts)
neg.norm_counts <- cbind("feature" = feature_list, neg.norm_counts)
# log counts
neg_log_counts <- as.data.frame(neg.norm_counts) %>% mutate(across(starts_with("DSP"),~ceiling(as.numeric(.x)))) %>% mutate(across(starts_with("DSP"),~log2(. + 1)))
## Q3 Normalization
q3.norm_counts <- norm.q3@assayData$q_norm
feature_list <- rownames(q3.norm_counts)
q3.norm_counts <- cbind("feature" = feature_list, q3.norm_counts)
# log counts
q3_log_counts <- as.data.frame(q3.norm_counts) %>% mutate(across(starts_with("DSP"),~ceiling(as.numeric(.x)))) %>% mutate(across(starts_with("DSP"),~log2(. + 1)))
# Export all count tables
export_counts <- FALSE
if(export_counts == TRUE){
write.csv(hk.norm_counts,
file.path(paste0(results.folder, "hk_norm_counts.csv")),
row.names = FALSE)
write.csv(neg.norm_counts,
file.path(paste0(results.folder, "neg_norm_counts.csv")),
row.names = FALSE)
write.csv(q3.norm_counts,
file.path(paste0(results.folder, "q3_norm_counts.csv")),
row.names = FALSE)
}
export.norm.counts <- FALSE
if(export.norm.counts == TRUE){
write.csv(neg.norm_counts,
file.path(paste0(results.folder,
"neg_norm_counts.csv")),
row.names = FALSE)
write.csv(neg_log_counts,
file.path(paste0(results.folder,
"neg_norm_log_counts.csv")),
row.names = FALSE)
}
```
# QC Plots for Marker Features Ki-67 and CD45
```{r}
# Set up the counts df for the marker features
library(dplyr)
# Marker features of interest
marker.features <- c("Ki-67", "CD45")
# Grab the normalized counts for both
marker.counts <- as.data.frame(neg_log_counts) %>%
filter(feature %in% marker.features)
# Make the Sample ID as rows
marker.counts.df <- as.data.frame((t(marker.counts)))
# Create a column for the Sample IDs and remove the .dcc
marker.counts.df$Sample_ID <- rownames(marker.counts.df)
# Remove the file extension .dcc
marker.counts.df$Sample_ID <- gsub("\\.dcc$", "", marker.counts.df$Sample_ID)
rownames(marker.counts.df) <- NULL
# Combine the counts with the annotation based on Sample ID
cleaned.annotation.df <- annotation.df[annotation.df$'slide name' != "No Template Control", ]
marker.boxplot.df <- merge(cleaned.annotation.df, marker.counts.df, by = "Sample_ID")
```
### Marker expression per Animal
```{r}
# Create QC boxplots for all marker features
# Organize annotation
marker.boxplot.df$animal_num <- as.factor(marker.boxplot.df$'Animal #')
# For each marker make a boxplot
for(marker in marker.features){
# Convert counts from character to numeric
marker.boxplot.df[[marker]] <- as.numeric(marker.boxplot.df[[marker]])
# Set the upper and lower y limits of the plot (log2 counts)
y.upper.limit <- max(marker.boxplot.df[[marker]]) + 0.5
y.lower.limit <- min(marker.boxplot.df[[marker]]) - 0.5
# Create a boxplot for for expression per animal #
animal.number.marker.boxplot <- ggplot(marker.boxplot.df, aes(x = animal_num, y = !!sym(marker), color = age)) +
geom_boxplot(notch = FALSE) +
ggtitle(paste0(marker, " expression per animal")) +
scale_y_continuous(labels = scales::comma) +
ylim(y.lower.limit, y.upper.limit) +
labs(x = "Animal #", y = paste0(marker, " log2 counts"))
# Export the marker expression by animal number boxplot
export.boxplot <- TRUE
if(export.boxplot == TRUE){
ggsave(paste0(project.folder.path, "qc/marker_qc_plots/", marker, "_boxplot_animal.png"), animal.number.marker.boxplot, width = 12, height = 10)
}
}
```
### Marker expression per ROI
```{r}
library(Polychrome)
# Reference for Polychrome:
# https://cran.r-project.org/web/packages/Polychrome/vignettes/creatingPalettes.html
# Add annotation for individual ROIs
marker.boxplot.df$animal_roi <- paste0(marker.boxplot.df$`Animal #`, "_", marker.boxplot.df$roi)
# For each marker make a boxplot
for(marker in marker.features){
# Convert counts from character to numeric
marker.boxplot.df[[marker]] <- as.numeric(marker.boxplot.df[[marker]])
# Set the upper and lower y limits of the plot (log2 counts)
y.upper.limit <- max(marker.boxplot.df[[marker]]) + 0.5
y.lower.limit <- min(marker.boxplot.df[[marker]]) - 0.5
# Separate by age
for(age.type in unique(marker.boxplot.df$age)){
# Subset the marker data by age
marker.boxplot.df.age <- marker.boxplot.df %>%filter(age == age.type)
# Create colors for each animal to distinguish the ROIs
animal.numbers <- unique(marker.boxplot.df.age$animal_num)
animal.num.colors <- unname(createPalette(length(animal.numbers),
c("#ff0000", "#00ff00", "#0000ff"),
M = 1000,
range = c(10,70)))
# Create the new boxplot by age
roi.marker.boxplot <- ggplot(marker.boxplot.df.age,
aes(x = animal_roi,
y = !!sym(marker),
color = animal_num)) +
geom_boxplot(notch = FALSE) +
ggtitle(paste0(marker, " expression per roi in ", age.type)) +
scale_y_continuous(labels = scales::comma) +
ylim(y.lower.limit, y.upper.limit) +
labs(x = "Animal#_ROI", y = paste0(marker, " log2 counts")) +
theme(axis.text.x = element_text(size = 8, angle = 90)) +
facet_wrap(.~treatment, scales = "free_x") +
scale_color_manual(values=animal.num.colors)
# Export the boxplot named by age
export.age.boxplot <- TRUE
if(export.age.boxplot == TRUE){
ggsave(paste0(project.folder.path, "qc/marker_qc_plots/", marker, "_boxplot_roi_", age.type, ".png"), roi.marker.boxplot, width = 12, height = 10)
}
}
# Create a boxplot for for expression per animal #
roi.combined.marker.boxplot <- ggplot(marker.boxplot.df, aes(x = animal_roi, y = !!sym(marker), color = treatment)) +
geom_boxplot(notch = FALSE) +
ggtitle(paste0(marker, " expression per roi")) +
scale_y_continuous(labels = scales::comma) +
ylim(y.lower.limit, y.upper.limit) +
labs(x = "Animal #", y = paste0(marker, " log2 counts")) +
theme(axis.text.x = element_text(size = 5, angle = 90)) +
facet_wrap(.~age, scales = "free_x")
# Export the marker expression by animal number boxplot
export.combined.boxplot <- TRUE
if(export.combined.boxplot == TRUE){
ggsave(paste0(project.folder.path, "qc/marker_qc_plots/", marker, "_boxplot_roi_combined.png"), roi.combined.marker.boxplot, width = 12, height = 10)
}
}
```
# QC plots for Nuclei Count
### Nuclei count per ROI
```{r}
# Convert nuclei counts from to a numeric column with no spaces
marker.boxplot.df$`nuclei` <- as.numeric(marker.boxplot.df$`Nuclei count`)
# Set the upper and lower y limits of the plot (log2 counts)
y.upper.limit <- max(marker.boxplot.df$`nuclei`) + 10
y.lower.limit <- min(marker.boxplot.df$`nuclei`) - 10
# Separate by age
for(age.type in unique(marker.boxplot.df$age)){
# Subset the marker data by age
marker.boxplot.df.age <- marker.boxplot.df %>% filter(age == age.type)
# Subset the marker data by age
marker.boxplot.df.age <- marker.boxplot.df %>%filter(age == age.type)
# Create colors for each animal to distinguish the ROIs
# Reference for Polychrome:
# https://cran.r-project.org/web/packages/Polychrome/vignettes/creatingPalettes.html
animal.numbers <- unique(marker.boxplot.df.age$animal_num)
animal.num.colors <- unname(createPalette(length(animal.numbers),
c("#ff0000", "#00ff00", "#0000ff"),
M = 1000,
range = c(10,70)))
# Create the new boxplot by age
roi.nuclei.boxplot <- ggplot(marker.boxplot.df.age, aes(x = animal_roi, y = nuclei, color = animal_num)) +
geom_boxplot(notch = FALSE) +
ggtitle(paste0("Nuclei count per roi in ", age.type)) +
scale_y_continuous(labels = scales::comma) +
ylim(y.lower.limit, y.upper.limit) +
labs(x = "Animal#_ROI", y = "Nuclei count") +
theme(axis.text.x = element_text(size = 8, angle = 90)) +
facet_wrap(.~treatment, scales = "free_x") +
scale_color_manual(values = animal.num.colors)
# Export the boxplot named by age
export.age.boxplot <- TRUE
if(export.age.boxplot == TRUE){
ggsave(paste0(project.folder.path, "qc/nuclei_qc_plots/boxplot_nuclei_roi_", age.type, ".png"), roi.nuclei.boxplot, width = 12, height = 12)
}
}
```
```{r}
# Create the boxplot per animal number
ki67.barplot.df$`animal_num` <- as.factor(ki67.barplot.df$`Animal #`)
ki67.boxplot.animal <- ggplot(ki67.barplot.df, aes(x = animal_num, y = Ki_67)) +
geom_boxplot(notch = FALSE) +
ggtitle("Ki-67 expression per animal") +
scale_y_continuous(labels = scales::comma) +
ylim(0, 30000)
# Export the boxplot
export.boxplot <- FALSE
if(export.boxplot == TRUE){
ggsave(paste0(project.folder.path, "results/ki67_boxplot_animal.png"), ki67.boxplot.animal, width = 12, height = 10)
}
```
# Additional box/bar plots for CD45
```{r}
# Make the boxplots for CD45
# Set up the normalized counts
# Grab the counts
cd45.counts <- hk.norm_counts["CD45", , drop = FALSE]
# Make the Sample ID as rows
cd45.counts.df <- as.data.frame(t(cd45.counts))
# Create a column for the Sample IDs and remove the .dcc
cd45.counts.df$Sample_ID <- rownames(cd45.counts.df)
cd45.counts.df$Sample_ID <- gsub("\\.dcc$", "", cd45.counts.df$Sample_ID)
rownames(cd45.counts.df) <- NULL
# Combine the counts with the annotation based on Sample ID
cd45.barplot.df <- merge(cleaned.annotation.df, cd45.counts.df, by = "Sample_ID")
cd45.barplot.df$`CD45` <- as.numeric(cd45.barplot.df$`CD45`)
# Create the boxplots for the two age groups, then combine into a single image
#cd45.barplot.df.old <- cd45.barplot.df[cd45.barplot.df$age == "old", ]
#cd45.barplot.df.young <- cd45.barplot.df[cd45.barplot.df$age == "young", ]
#cd45.boxplot.old <- ggplot(cd45.barplot.df.old, aes(x = treatment, y = CD45)) +
# geom_boxplot(notch = FALSE) +
# ggtitle("Old") +
# scale_y_continuous(labels = scales::comma) +
# ylim(0, 30000)
#cd45.bp.old.plotly <- plotly::ggplotly(cd45.boxplot.old)
#cd45.boxplot.young <- ggplot(cd45.barplot.df.young, aes(x = treatment, y = CD45)) +
# geom_boxplot(notch = FALSE) +
# ggtitle("Young") +
# scale_y_continuous(labels = scales::comma) +
# ylim(0, 30000)
#cd45.combined.boxplot <- grid.arrange(cd45.boxplot.young, cd45.boxplot.old, ncol = 2)
#title <- textGrob("CD45 signal by Age and Treatment", gp = gpar(fontsize = 20, fontface = "bold"))
#final.cd45.boxplot <- grid.arrange(title, cd45.combined.boxplot, heights = c(0.1, 0.9))
#grid.draw(final.cd45.boxplot)
#export.boxplot <- FALSE
#if(export.boxplot == TRUE){
# ggsave(paste0(project.folder.path, "results/cd45_boxplot_age.png"), final.cd45.boxplot, width = 12, height = 10)
#}
# Create the boxplot per animal number
cd45.barplot.df$`animal_num` <- as.factor(cd45.barplot.df$`Animal #`)
cd45.boxplot.animal <- ggplot(cd45.barplot.df, aes(x = animal_num, y = CD45)) +
geom_boxplot(notch = FALSE) +
ggtitle("CD45 expression per animal") +
scale_y_continuous(labels = scales::comma) +
ylim(0, 30000)
# Export the boxplot
export.boxplot <- FALSE
if(export.boxplot == TRUE){
ggsave(paste0(project.folder.path, "results/cd45_boxplot_animal.png"), cd45.boxplot.animal, width = 12, height = 10)
}
# Boxplot for Nuclei count per ROI and Ki-67 expression
ki67.barplot.df$`nuclei` <- as.numeric(ki67.barplot.df$`Nuclei count`)
ki67.barplot.df$animal_roi <- paste0(ki67.barplot.df$`Animal #`, "_", ki67.barplot.df$roi)
# Create a plot labeled for plotly
ki67.nuclei.dot.plotly <- ggplot(ki67.barplot.df,
aes(x = nuclei, y = Ki_67, text = paste0("Animal_ROI: ", animal_roi))) +
geom_point() +
labs(x = "Nuclei Count",
y = "Ki-67 Expression",
title = "Nuclei Count by Ki-67 Expression")
# Visualize the plotly plot
ggplotly(ki67.nuclei.dot.plotly)
# Create a plot without a trend line
ki67.nuclei.dot.plot <- ggplot(ki67.barplot.df,
aes(x = nuclei, y = Ki_67)) +
geom_point() +
labs(x = "Nuclei Count",
y = "Ki-67 Expression",
title = "Nuclei Count by Ki-67 Expression")
# Export the basic dot plot
export.dotplot <- FALSE
if(export.dotplot == TRUE){
ggsave(paste0(project.folder.path, "results/ki67_nuclei_dotplot.png"), ki67.nuclei.dot.plot, width = 9, height = 8)
}
# Create a plot with a trend line
ki67.nuclei.dot.plot.trend <- ggplot(ki67.barplot.df,
aes(x = nuclei, y = Ki_67)) +
geom_point() +
geom_smooth(method = "lm", formula = y ~ x, se = TRUE) +
labs(x = "Nuclei Count",
y = "Ki-67 Expression",
title = "Nuclei Count by Ki-67 Expression")
# Check if there is a relationship between nuclei and CD45 expression
cor.test(ki67.barplot.df$nuclei, ki67.barplot.df$Ki_67, method = "spearman")
# Create the plot of expression per ROI
ki67.boxplot.animal.roi <- ggplot(ki67.barplot.df, aes(x = animal_roi, y = Ki_67)) +
geom_boxplot(notch = FALSE) +
ggtitle("Ki-67 expression per animal") +
scale_y_continuous(labels = scales::comma) +
ylim(0, 30000)
# Export the boxplot
export.boxplot <- FALSE
if(export.boxplot == TRUE){
ggsave(paste0(project.folder.path, "results/ki67_boxplot_animal.png"), ki67.boxplot.animal, width = 12, height = 10)
}
# Boxplot for Nuclei count per ROI and CD45 expression
cd45.barplot.df$`nuclei` <- as.numeric(cd45.barplot.df$`Nuclei count`)
cd45.barplot.df$animal_roi <- paste0(cd45.barplot.df$`Animal #`, "_", cd45.barplot.df$roi)
# Create a plot labeled for plotly
cd45.nuclei.dot.plotly <- ggplot(cd45.barplot.df,
aes(x = nuclei, y = CD45, text = paste0("Animal_ROI: ", animal_roi))) +
geom_point() +
labs(x = "Nuclei Count",
y = "CD45 Expression",
title = "Nuclei Count by CD45 Expression")
# Visualize the plotly plot
ggplotly(cd45.nuclei.dot.plot)
# Create a plot with a trend line
cd45.nuclei.dot.plot <- ggplot(cd45.barplot.df,
aes(x = nuclei, y = CD45)) +
geom_point() +
labs(x = "Nuclei Count",
y = "CD45 Expression",
title = "Nuclei Count by CD45 Expression")
# Export the basic dot plot
export.dotplot <- FALSE
if(export.dotplot == TRUE){
ggsave(paste0(project.folder.path, "results/cd45_nuclei_dotplot.png"), cd45.nuclei.dot.plot, width = 9, height = 8)
}
# Create a plot with a trend line
cd45.nuclei.dot.plot.trend <- ggplot(cd45.barplot.df,
aes(x = nuclei, y = CD45)) +
geom_point() +
geom_smooth(method = "lm", formula = y ~ x, se = TRUE) +
labs(x = "Nuclei Count",
y = "CD45 Expression",
title = "Nuclei Count by CD45 Expression")
# Check if there is a relationship between nuclei and CD45 expression
cor.test(cd45.barplot.df$nuclei, cd45.barplot.df$CD45, method = "spearman")
# Create the boxplot per ROI
cd45.barplot.df$`animal_num` <- as.factor(cd45.barplot.df$`Animal #`)
cd45.boxplot.animal <- ggplot(cd45.barplot.df, aes(x = animal_num, y = CD45)) +
geom_boxplot(notch = FALSE) +
ggtitle("CD45 expression per animal") +
scale_y_continuous(labels = scales::comma) +
ylim(0, 30000)
# Export the boxplot
export.boxplot <- FALSE
if(export.boxplot == TRUE){
ggsave(paste0(project.folder.path, "results/cd45_boxplot_animal.png"), cd45.boxplot.animal, width = 12, height = 10)
}
# Create bar plot for nuclei count per ROI
# Boxplot for Nuclei count per ROI and Ki-67 expression
ki67.barplot.df$`nuclei` <- as.numeric(ki67.barplot.df$`Nuclei count`)
# Create a plot labeled for plotly
nuclei.roi.bar.plot <- ggplot(ki67.barplot.df,
aes(x = animal_roi, y = nuclei, fill = animal_num)) +
geom_bar(stat = "identity") +
labs(x = "ROI",
y = "Nuclei Count",
title = "Nuclei Count by ROI Expression") +
theme(axis.text.x = element_text(size = 6))
nuclei.roi.bar.plot <- ggplot(ki67.barplot.df,
aes(x = animal_roi, y = nuclei)) +
geom_bar(stat = "identity") +
labs(x = "ROI",