```r
#read in the output of bedtools intersect
cluster_TEs <- read.table("output/18-Apul-piRNA/0_piRNA_pipeline_proTRAC/APUL_piRNA_clusters_TEs_intersect.txt")

#repeat analysis as above with piRNA cluster TEs
cluster_TEs$V8 <- gsub("/.*","",cluster_TEs$V8)
cluster_TEs$V8 <- gsub("unclear","Unknown",cluster_TEs$V8)
table_of_cluster_TEs <- as.data.frame(table(cluster_TEs$V8))
table_of_cluster_TEs <- table_of_cluster_TEs[(!grepl("Low_complexity", table_of_cluster_TEs$Var1)),]
table_of_cluster_TEs <- table_of_cluster_TEs[(!grepl("Simple_repeat", table_of_cluster_TEs$Var1)),]
cols <- rainbow(nrow(table_of_cluster_TEs))
table_of_cluster_TEs$percent = round(100*table_of_cluster_TEs$Freq/sum(table_of_cluster_TEs$Freq), digits = 1)
table_of_cluster_TEs$label = paste(table_of_cluster_TEs$Var1," (", table_of_cluster_TEs$percent,"%)", sep = "")

#generate stacked barplot showing TE distribution of clusters vs whole genome
table_of_TEs$origin <- "genome"
table_of_cluster_TEs$origin <- "cluster"
clust <- table_of_cluster_TEs[,c(5,1,3)]
genome <- table_of_TEs[,c(5,1,3)]
all <- rbind(clust, genome)
colnames(all)[2] <- "family"

# Stacked barplot
my.stack.out <- paste0("output/18-Apul-piRNA/2_TE_piRNA_cluster_overlap/", my.outprefix,"cluster_stack_plot.pdf")
#pdf(my.stack.out)
ggplot(all, aes(fill=family, y=percent, x=origin)) + 
  geom_bar(position="stack", stat="identity") + theme_bw() +
  coord_flip() 
```

<img src="18.2-Apul-piRNA-TE-overlap_files/figure-html/unnamed-chunk-3-1.png" width="672" />

```r
#dev.off()
```