From 2c0450a1945086e9e2c84f45d4820f207ed943f8 Mon Sep 17 00:00:00 2001
From: Matthew Madany <matthew.madany@gmail.com>
Date: Tue, 19 May 2020 20:32:42 -0700
Subject: [PATCH] Update analysis.R

---
 analysis.R | 2235 ++++++++++++++++++++++++++++++++++++++++------------
 1 file changed, 1730 insertions(+), 505 deletions(-)

diff --git a/analysis.R b/analysis.R
index 5753f21..343b501 100644
--- a/analysis.R
+++ b/analysis.R
@@ -1,505 +1,1730 @@
-setwd("~/Neuron_Rush_Sep/oct_more")
-require('readxl')
-require('ggplot2')
-require('plyr')
-require('gridExtra')
-require('ggpubr')
-require('cowplot')
-require('wesanderson')
-
-# import data from 3 brain areas
-# synaptic vesicle data
-LHBves = read_excel("Lateral_Habenula_VesicleData.xls")
-NUCves = read_excel("Nucleas_Accumbens_VesicleData_re2.xls")
-VENves = read_excel("Ventral_Palladum_VesicleData.xls")
-  
-# bouton data
-LHBterm = read_excel("Lateral_Habenula_T_Summary_Data.xls")
-NUCterm <- read_excel("Nucleas_Accumbens_T_Summary_Data_re2.xls")
-VENterm <- read_excel("Ventral_Palladum_T_Summary_Data.xls")
-
-# qualitative analysis data
-NUCType <- read_excel("Summary_Boutons_3Areas_AZneeded.xlsx")
-LHBType <- read_excel("Summary_Boutons_3Areas_AZneeded.xlsx",sheet = 2)
-VENType <- read_excel("Summary_Boutons_3Areas_AZneeded.xlsx",sheet = 3)
-
-NUCType$`Bouton ID`<-as.numeric(substring(NUCType$`Bouton ID`, 2))
-LHBType$`Bouton ID`<-as.numeric(substring(LHBType$`Bouton ID`, 2))
-VENType$`Bouton ID`<-as.numeric(substring(VENType$`Bouton ID`, 2))
-
-NUCAuto <- read_excel("Nucleas_Accumbens_AutoBoutonData.xls")
-
-## Reset Accumbens with Auto Bouton Data
-reNUC <- NUCType
-uids <- unique(NUCAuto$`Terminal ID in AutoBouton Labels`)
-addData <- data.frame(matrix(data=NA,nrow=length(uids)-nrow(reNUC),ncol = ncol(reNUC)))
-names(addData) <- names(reNUC)
-reNUC <- rbind(reNUC,addData)
-reNUC$`Bouton ID` <- uids
-reNUC$`Bouton Type` <- NA
-for (i in 1:length(reNUC$`Bouton ID`)){
-  iddx <- reNUC$`Bouton ID`[i]
-  idens <- NUCAuto[NUCAuto$`Terminal ID in AutoBouton Labels`==iddx,]
-  idens <- idens[order(idens$nVoxels),]
-  idens
-  
-  chk <- idens[1,2]
-  if (chk %in% c(10, 9 ,4)){chk <- idens[2,2]}
-  if (is.na(chk)){
-    reNUC$`Post-synaptic element`[i] <- "?"
-    reNUC$`Type of Synapse`[i] <- "?"
-    reNUC$`Bouton Type` <- "En passant"
-    next
-  }
-  if (chk == 5) {
-    reNUC$`Post-synaptic element`[i] <- "Dendrite"
-    reNUC$`Type of Synapse`[i] <- "S"
-    reNUC$`Bouton Type` <- "S"
-  }
-  if (chk==1) {
-    reNUC$`Post-synaptic element`[i] <- "Dendrite"
-    reNUC$`Type of Synapse`[i] <- "S"
-    reNUC$`Bouton Type` <- "S"
-  }  
-  if (chk==2) {
-    reNUC$`Post-synaptic element`[i] <- "Dendrite"
-    reNUC$`Type of Synapse`[i] <- "AS"
-    reNUC$`Bouton Type` <- "Terminal"
-  }  
-  if (chk==3) {
-    reNUC$`Post-synaptic element`[i] <- "Spine"
-    reNUC$`Type of Synapse`[i] <- "S"
-    reNUC$`Bouton Type` <- "S"
-  }  
-  if (chk==6) {
-    reNUC$`Post-synaptic element`[i] <- "Spine"
-    reNUC$`Type of Synapse`[i] <- "AS"
-    reNUC$`Bouton Type` <- "AS"
-  }  
-  if (chk==7) {
-    reNUC$`Post-synaptic element`[i] <- "Dendrite"
-    reNUC$`Type of Synapse`[i] <- "AS"
-    reNUC$`Bouton Type` <- "AS"
-  }  
-  if (chk==8) {
-    reNUC$`Post-synaptic element`[i] <- "Spine"
-    reNUC$`Type of Synapse`[i] <- "AS"
-    reNUC$`Bouton Type` <- "AS"
-  }  
-  if (chk==11) {
-    reNUC$`Post-synaptic element`[i] <- "?"
-    reNUC$`Type of Synapse`[i] <- "?"
-    reNUC$`Bouton Type` <- "En passant"
-  } 
-}
-NUCType <- reNUC
-
-## Vesicle Vol Fractions
-#NUC
-vesNUC <- data.frame(matrix(ncol = 9, nrow = 0))
-names(vesNUC) <- c('Vesicular Volume Fraction','Miotchondrial Volume Faction','Area',
-                   'Synapse Type','Post-synaptic Element','Vesicle Count', 'Vesicle Cloud Density','ID','Terminal Size')
-a = 1
-for (i in 1:length(NUCType$`Bouton ID`)){
-  if (!(NUCType$`Bouton ID`[i] %in% NUCterm$`Terminal ID`)){
-    next
-  }
-  vs <- sum((4/3)*(NUCves[NUCves$`Terminal ID - which terminal the vesicle is in` ==NUCType$`Bouton ID`[i],]$`Size(nm) - represented as spherical radius`)^3)
-  vs = vs / NUCterm[NUCterm$`Terminal ID`==NUCType$`Bouton ID`[i],]$`Terminal Volume (nm^3)`
-  mf = NUCterm[NUCterm$`Terminal ID`==NUCType$`Bouton ID`[i],]$`Total Mito Volume (nm^3)` /NUCterm[NUCterm$`Terminal ID`==NUCType$`Bouton ID`[i],]$`Terminal Volume (nm^3)`
-  ty = NUCType[NUCType$`Bouton ID` == NUCType$`Bouton ID`[i],]$`Type of Synapse`
-  pe = NUCType[NUCType$`Bouton ID` == NUCType$`Bouton ID`[i],]$`Post-synaptic element`
-  vesNUC[a,]$`Vesicular Volume Fraction` <- vs
-  vesNUC[a,]$`Miotchondrial Volume Faction` <- mf
-  vesNUC[a,]$`Area` <- 'Nucleus Accumbens'
-  vesNUC[a,]$`Synapse Type` <- ty[1]
-  vesNUC[a,]$`Post-synaptic Element` <- pe[1]
-  vesNUC[a,]$ID <- NUCType$`Bouton ID`[i]
-  vesNUC[a,]$`Vesicle Count`<- nrow(NUCves[NUCves$`Terminal ID - which terminal the vesicle is in` == NUCType$`Bouton ID`[i],])
-  vesNUC[a,]$`Vesicle Cloud Density` <- vesNUC[a,]$`Vesicle Count` / ((NUCterm[NUCterm$`Terminal ID`==NUCType$`Bouton ID`[i],]$`Terminal Volume (nm^3)` -
-                                                                         NUCterm[NUCterm$`Terminal ID`==NUCType$`Bouton ID`[i],]$`Total Mito Volume (nm^3)`)*10^-9 )
-  vesNUC[a,]$`Terminal Size` <- NUCterm[NUCterm$`Terminal ID`==NUCType$`Bouton ID`[i],]$`Terminal Volume (nm^3)`
-  #vesNUC[a,]$`Bouton Type` <- NUCType$`Bouton Type`[i]
-  
-  
-  a = a+1
-}
-#LHB
-vesLHB <- data.frame(matrix(ncol = 9, nrow = 0))
-names(vesLHB) <- c('Vesicular Volume Fraction','Miotchondrial Volume Faction','Area',
-                   'Synapse Type','Post-synaptic Element','Vesicle Count', 'Vesicle Cloud Density','ID','Terminal Size')
-a = 1
-for (i in 1:length(LHBType$`Bouton ID`)){
-  if (!(LHBType$`Bouton ID`[i] %in% LHBterm$`Terminal ID`)){
-    next
-  }
-  vs <- sum((4/3)*(LHBves[LHBves$`Terminal ID - which terminal the vesicle is in` ==LHBType$`Bouton ID`[i],]$`Size(nm) - represented as spherical radius`)^3)
-  vs = vs / LHBterm[LHBterm$`Terminal ID`==LHBType$`Bouton ID`[i],]$`Terminal Volume (nm^3)`
-  mf = LHBterm[LHBterm$`Terminal ID`==LHBType$`Bouton ID`[i],]$`Total Mito Volume (nm^3)` /LHBterm[LHBterm$`Terminal ID`==LHBType$`Bouton ID`[i],]$`Terminal Volume (nm^3)`
-  ty = LHBType[LHBType$`Bouton ID` == LHBType$`Bouton ID`[i],]$`Type of Synapse`
-  pe = LHBType[LHBType$`Bouton ID` == LHBType$`Bouton ID`[i],]$`Post-synaptic element`
-  vesLHB[a,]$`Vesicular Volume Fraction` <- vs[1]
-  vesLHB[a,]$`Miotchondrial Volume Faction` <- mf[1]
-  vesLHB[a,]$`Area` <- 'Lateral Habenula'
-  vesLHB[a,]$`Synapse Type` <- ty
-  vesLHB[a,]$`Post-synaptic Element` <- pe
-  vesLHB[a,]$ID <- LHBType$`Bouton ID`[i]
-  vesLHB[a,]$`Vesicle Count`<- nrow(LHBves[LHBves$`Terminal ID - which terminal the vesicle is in` == LHBType$`Bouton ID`[i],])
-  vesLHB[a,]$`Vesicle Cloud Density` <- vesLHB[a,]$`Vesicle Count` / ((LHBterm[LHBterm$`Terminal ID`==LHBType$`Bouton ID`[i],][1,1]$`Terminal Volume (nm^3)` -
-                                                                        LHBterm[LHBterm$`Terminal ID`==LHBType$`Bouton ID`[i],]$`Total Mito Volume (nm^3)`[1])*10^-9 )
-  vesLHB[a,]$`Terminal Size` <- LHBterm[LHBterm$`Terminal ID`==LHBType$`Bouton ID`[i],][1,1]$`Terminal Volume (nm^3)`
-  
-  
-  
-  a = a+1
-}
-
-#VEN
-vesVEN <- data.frame(matrix(ncol = 9, nrow = 0))
-names(vesVEN) <- c('Vesicular Volume Fraction','Miotchondrial Volume Faction','Area',
-                   'Synapse Type','Post-synaptic Element','Vesicle Count', 'Vesicle Cloud Density','ID','Terminal Size')
-a = 1
-for (i in 1:length(VENType$`Bouton ID`)){
-  if (!(VENType$`Bouton ID`[i] %in% VENterm$`Terminal ID`)){
-    next
-  }
-  vs <- sum((4/3)*(VENves[VENves$`Terminal ID - which terminal the vesicle is in` ==VENType$`Bouton ID`[i],]$`Size(nm) - represented as spherical radius`)^3)
-  vs = vs / VENterm[VENterm$`Terminal ID`==VENType$`Bouton ID`[i],]$`Terminal Volume (nm^3)`
-  mf = VENterm[VENterm$`Terminal ID`==VENType$`Bouton ID`[i],]$`Total Mito Volume (nm^3)` /VENterm[VENterm$`Terminal ID`==VENType$`Bouton ID`[i],]$`Terminal Volume (nm^3)`
-  ty = VENType[VENType$`Bouton ID` == VENType$`Bouton ID`[i],]$`Type of Synapse`
-  pe = VENType[VENType$`Bouton ID` == VENType$`Bouton ID`[i],]$`Post-synaptic element`
-  vesVEN[a,]$`Vesicular Volume Fraction` <- vs
-  vesVEN[a,]$`Miotchondrial Volume Faction` <- mf
-  vesVEN[a,]$`Area` <- 'Ventral Pallidum'
-  vesVEN[a,]$`Synapse Type` <- ty
-  vesVEN[a,]$`Post-synaptic Element` <- pe
-  vesVEN[a,]$ID <- VENType$`Bouton ID`[i]
-  vesVEN[a,]$`Vesicle Count`<- nrow(VENves[VENves$`Terminal ID - which terminal the vesicle is in` == VENType$`Bouton ID`[i],])
-  vesVEN[a,]$`Vesicle Cloud Density` <- vesVEN[a,]$`Vesicle Count` / ((VENterm[VENterm$`Terminal ID`==VENType$`Bouton ID`[i],]$`Terminal Volume (nm^3)` -
-                                                                         VENterm[VENterm$`Terminal ID`==VENType$`Bouton ID`[i],]$`Total Mito Volume (nm^3)`)*10^-9 )
-  
-  vesVEN[a,]$`Terminal Size` <- VENterm[VENterm$`Terminal ID`==VENType$`Bouton ID`[i],]$`Terminal Volume (nm^3)`
-  
-  
-  a = a+1
-}
-
-
-
-combdf <- rbind(vesLHB,vesNUC,vesVEN)
-combdf <- na.omit(combdf)
-
-
-
-#thickness of lines around subplots
-sb = .2
-
-# 3plots for type of synapse plot ## SYMMETRIC VS ASYMMETRIC
-pal2 = c("#d6b629","#ff00a5","#002bff")
-pal1 = c("#CE1DE2", "#19e6df")
-
-tydf <- combdf[combdf$`Synapse Type` == 'AS' | combdf$`Synapse Type` == 'S',]
-mu <- ddply(tydf, "`Synapse Type`", summarise, grp.mean=mean(`Miotchondrial Volume Faction`))
-mu2 <- ddply(tydf, "`Synapse Type`", summarise, grp.mean=mean(`Vesicle Count`))
-mu3 <- ddply(tydf, "`Synapse Type`", summarise, grp.mean=mean(`Vesicle Cloud Density`))
-
-pdf('Synapse_Type_Multi5.pdf',width=16,height=14,onefile = TRUE)
-p1 <- ggplot(tydf, aes(x=tydf$`Miotchondrial Volume Faction`, fill=tydf$`Synapse Type`))+ 
-  geom_density(aes(x=tydf$`Miotchondrial Volume Faction`,y=..density..),alpha=.05) +
-  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.15,binwidth = .04) +
-  geom_vline(data=mu, aes(xintercept=grp.mean, color=mu$`Synapse Type`),
-             linetype="dashed",show.legend = FALSE) +
-  xlim(0,.45) + xlab("Mitochondrial Volume Fraction") + ylab("Density")+ 
-  ggtitle("Mitochondrial Volume Proportion of Boutons") +
-  theme(legend.position = "left",plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb)) +  labs(fill = "Synapse Type") +
-  scale_fill_manual(values=pal1, labels = c('Asymmetric','Symmetric')) + 
-  scale_color_manual(values = pal1)
-  #scale_fill_discrete(labels= c('Asymmetric','Symmetric'), values = pal1)
-
-## faceted vesicle count + vesicle cloud density + mito frac
-p2 <- ggplot(tydf, aes(x=tydf$`Vesicle Count`, fill=tydf$`Synapse Type`))+ 
-  geom_density(aes(x=tydf$`Vesicle Count`,y=..density..),alpha=.05) +
-  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.15,binwidth = 250) +
-  geom_vline(data=mu2, aes(xintercept=grp.mean, color=mu$`Synapse Type`),
-             linetype="dashed",show.legend = FALSE) +
-  xlab("Number of Vesicles inside Terminal") + ylab("Density") +
-  labs(fill = "Synapse Type") +
-  ggtitle("Synaptic Vesicle Counts per Bouton") +
-  theme(plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb))+
-  scale_fill_manual(values=pal1, labels = c('Asymmetric','Symmetric')) +
-  guides(fill=FALSE)+ 
-  scale_color_manual(values = pal1)
-
-p3 <- ggplot(tydf, aes(x=tydf$`Vesicle Cloud Density`, fill=tydf$`Synapse Type`))+ 
-  geom_density(aes(x=tydf$`Vesicle Cloud Density`,y=..density..),alpha=.05) +
-  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.15,binwidth = 400) +
-  geom_vline(data=mu3, aes(xintercept=grp.mean, color=mu$`Synapse Type`),
-             linetype="dashed",show.legend = FALSE) +
-  xlab(expression(Vesicle~Count~Divided~by~Terminal~Volume~(N[vesicles]/??m^3))) +
-  ylab("Density") +
-  xlim(300,NA)+
-  labs(fill = "Synapse Type") +
-  ggtitle("Vesicle Cloud Solidity") +
-  theme(plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb))+
-  scale_fill_manual(values=pal1, labels = c('Asymmetric','Symmetric')) +
-  guides(fill=FALSE)+ 
-  scale_color_manual(values = pal1)
-
-
-## 3plots for type of synapse plot ## TARGET
-
-aind <- combdf$`Post-synaptic Element` =='Dendrite' | combdf$`Post-synaptic Element` =='Spine' | combdf$`Post-synaptic Element` =='Cell Body'
-aind <- replace(aind,is.na(aind),FALSE)
-atydf <- combdf[aind,]
-amu <- ddply(tydf, "`Post-synaptic Element`", summarise, grp.mean=mean(`Miotchondrial Volume Faction`))
-amu2 <- ddply(tydf, "`Post-synaptic Element`", summarise, grp.mean=mean(`Vesicle Count`))
-amu3 <- ddply(tydf, "`Post-synaptic Element`", summarise, grp.mean=mean(`Vesicle Cloud Density`))
-
-#pdf('testpostsyn.pdf')
-p4 <- ggplot(atydf, aes(x=atydf$`Miotchondrial Volume Faction`, fill=atydf$`Post-synaptic Element`))+ 
-  geom_density(aes(x=atydf$`Miotchondrial Volume Faction`,y=..density..),alpha=.2) +
-  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.3,binwidth = .03) +
-  geom_vline(data=amu, aes(xintercept=grp.mean, color=amu$`Post-synaptic Element`),
-             linetype="dashed",show.legend = FALSE) +
-  xlim(0,.45) + xlab("Mitochondrial Volume Fraction") + ylab("Density")+ 
-  #ggtitle("Mitochondrial Volume Porportion of Boutons") +
-  theme(legend.position = "left",plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb)) +  
-  labs(fill = "Post-synaptic Element") +#+
-  scale_fill_manual(values=pal2)+ 
-  scale_color_manual(values = pal2)
-#p4
-#dev.off()
-
-## faceted vesicle count + vesicle cloud density + mito frac
-p5 <- ggplot(atydf, aes(x=atydf$`Vesicle Count`, fill=atydf$`Post-synaptic Element`))+ 
-  geom_density(aes(x=atydf$`Vesicle Count`,y=..density..),alpha=.2) +
-  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.3,binwidth = 250) +
-  geom_vline(data=amu2, aes(xintercept=grp.mean, color=amu2$`Post-synaptic Element`),
-             linetype="dashed",show.legend = FALSE) +
-  xlab("Number of Vesicles inside Terminal") + ylab("Density") +
-  labs(fill = "Post-synaptic Element") +
-  scale_fill_manual(values=pal2) +
-  theme(plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb))+
-  guides(fill=FALSE)+ 
-  scale_color_manual(values = pal2)
-
-p6 <- ggplot(atydf, aes(x=atydf$`Vesicle Cloud Density`, fill=atydf$`Post-synaptic Element`))+ 
-  geom_density(aes(x=atydf$`Vesicle Cloud Density`,y=..density..),alpha=.2) +
-  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.3,binwidth = 350) +
-  geom_vline(data=amu3, aes(xintercept=grp.mean, color=amu3$`Post-synaptic Element`),
-             linetype="dashed",show.legend = FALSE) +
-  xlab(expression(Vesicle~Count~Divided~by~Terminal~Volume~(N[vesicles]/??m^3))) +
-  ylab("Density") +
-  xlim(300,3200)+
-  labs(fill = "Post-synaptic Element") +
-  scale_fill_manual(values=pal2) +
-  #ggtitle("Vesicle Cloud Solidity") +
-  theme(plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb))+
-  guides(fill=FALSE)+ 
-  scale_color_manual(values = pal2)
-
-
-## 3 Plots for AREA  ######## 
-
-
-btydf <- combdf
-bmu <- ddply(tydf, "`Area`", summarise, grp.mean=mean(`Miotchondrial Volume Faction`))
-bmu2 <- ddply(tydf, "`Area`", summarise, grp.mean=mean(`Vesicle Count`))
-bmu3 <- ddply(tydf, "`Area`", summarise, grp.mean=mean(`Vesicle Cloud Density`))
-
-#pdf('testpostsyn.pdf')
-p7 <- ggplot(btydf, aes(x=btydf$`Miotchondrial Volume Faction`, fill=btydf$`Area`))+ 
-  geom_density(aes(x=btydf$`Miotchondrial Volume Faction`,y=..density..),alpha=.2) +
-  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.3,binwidth = .03) +
-  geom_vline(data=bmu, aes(xintercept=grp.mean, color=bmu$`Area`),
-             linetype="dashed",show.legend = FALSE) +
-  xlim(0,.45) + xlab("Mitochondrial Volume Fraction") + ylab("Density")+ 
-  #ggtitle("Mitochondrial Volume Porportion of Boutons") +
-  theme(legend.position = "left",plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb)) +  
-  labs(fill = "Area") #+#+
-  #scale_fill_manual(values=pal3)+ 
-  #scale_color_manual(values = pal3)
-#p4
-#dev.off()
-
-## faceted vesicle count + vesicle cloud density + mito frac
-p8 <- ggplot(btydf, aes(x=btydf$`Vesicle Count`, fill=btydf$`Area`))+ 
-  geom_density(aes(x=btydf$`Vesicle Count`,y=..density..),alpha=.2) +
-  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.3,binwidth = 250) +
-  geom_vline(data=bmu2, aes(xintercept=grp.mean, color=bmu2$`Area`),
-             linetype="dashed",show.legend = FALSE) +
-  xlab("Number of Vesicles inside Terminal") + ylab("Density") +
-  labs(fill = "Area") +
-  #scale_fill_manual(values=pal3) +
-  theme(plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb))+
-  guides(fill=FALSE)#+ 
-  #scale_color_manual(values = pal3)
-
-p9 <- ggplot(btydf, aes(x=btydf$`Vesicle Cloud Density`, fill=btydf$`Area`))+ 
-  geom_density(aes(x=btydf$`Vesicle Cloud Density`,y=..density..),alpha=.2) +
-  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.3,binwidth = 350) +
-  geom_vline(data=bmu3, aes(xintercept=grp.mean, color=bmu3$`Area`),
-             linetype="dashed",show.legend = FALSE) +
-  xlab(expression(Vesicle~Count~Divided~by~Terminal~Volume~(N[vesicles]/??m^3))) +
-  ylab("Density") +
-  xlim(300,3200)+
-  labs(fill = "Area") +
-  #scale_fill_manual(values=pal3) +
-  #ggtitle("Vesicle Cloud Solidity") +
-  theme(plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb))+
-  guides(fill=FALSE)
-  #scale_color_manual(values = pal3)
-
-#grid.arrange(arrangeGrob(p1,p2,p3,ncol=3))
-plot_grid(p1,p2,p3,p4,p5,p6,p7,p8,p9,nrow = 3,ncol = 3,rel_widths = c(1-(.33+.29),.29,.33),labels="AUTO",label_size = 16)
-dev.off()
-
-#means and errors
-tydf <- combdf[combdf$`Synapse Type` == 'AS' | combdf$`Synapse Type` == 'S',]
-mu <- ddply(tydf, "`Synapse Type`", summarise, grp.mean=mean(`Miotchondrial Volume Faction`),grp.sd=sd(`Miotchondrial Volume Faction`))
-mu2 <- ddply(tydf, "`Synapse Type`", summarise, grp.mean=mean(`Vesicle Count`),grp.sd=sd(`Vesicle Count`))
-mu3 <- ddply(tydf, "`Synapse Type`", summarise, grp.mean=mean(`Vesicle Cloud Density`),grp.sd=sd(`Vesicle Cloud Density`))
-
-btydf <- combdf
-bmu <- ddply(tydf, "`Area`", summarise, grp.mean=mean(`Miotchondrial Volume Faction`),grp.sd=sd(`Miotchondrial Volume Faction`))
-bmu2 <- ddply(tydf, "`Area`", summarise, grp.mean=mean(`Vesicle Count`),grp.sd=sd(`Vesicle Count`))
-bmu3 <- ddply(tydf, "`Area`", summarise, grp.mean=mean(`Vesicle Cloud Density`),grp.sd=sd(`Vesicle Cloud Density`))
-
-aind <- combdf$`Post-synaptic Element` =='Dendrite' | combdf$`Post-synaptic Element` =='Spine' | combdf$`Post-synaptic Element` =='Cell Body'
-aind <- replace(aind,is.na(aind),FALSE)
-atydf <- combdf[aind,]
-amu <- ddply(tydf, "`Post-synaptic Element`", summarise, grp.mean=mean(`Miotchondrial Volume Faction`),grp.sd=sd(`Miotchondrial Volume Faction`))
-amu2 <- ddply(tydf, "`Post-synaptic Element`", summarise, grp.mean=mean(`Vesicle Count`),grp.sd=sd(`Vesicle Count`))
-amu3 <- ddply(tydf, "`Post-synaptic Element`", summarise, grp.mean=mean(`Vesicle Cloud Density`),grp.sd=sd(`Vesicle Cloud Density`))
-
-
-
-
-
-#pdf('Synapse_Type_Ves.pdf',width=5, height=4)
-ggplot(tydf, aes(x=tydf$`Vesicle Count` ,y=..scaled.., fill=tydf$`Synape Type`))+ 
-  geom_density(alpha=.2) +
-  xlim(0,NA) + xlab("Number of Vesicles per Terminal") + ylab("Density") +
-  labs(fill = "Synapse Type") +
-  ggtitle("Synaptic Vesicle Counts of Boutons")+
-  scale_fill_discrete(labels= c('Asymmetric','Symmetric'))+
-  xlim(NA,3500)
-#dev.off()
-
-pdf('Synapse_Type_Cloud2.pdf',width=3, height=3)
-ggplot(tydf, aes(x=tydf$`Vesicle Cloud Density` ,y=..scaled.., fill=tydf$`Synape Type`))+ 
-  geom_density(alpha=.2) +
-  xlim(0,NA) + 
-  xlab(expression(Vesicle~Count~Divided~by~Terminal~Volume~(N[vesicles]/??m[3]))) + 
-  ylab("Density") +
-  labs(fill = "Synapse Type") +
-  ggtitle("Vesicle Cloud Density by Synapse Type")+
-  scale_fill_discrete(labels= c('Asymmetric','Symmetric'))
-dev.off()
-
-
-
-## Mito Vol Fractions across Areas plot
-lhdf <- data.frame('Mitochondrial Volume Fraction' <- VENterm$`Total Mito Volume (nm^3)`/VENterm$`Terminal Volume (nm^3)`,'Area' <- 'Lateral Habenula')
-nudf <- data.frame('Mitochondrial Volume Fraction' <- NUCterm$`Total Mito Volume (nm^3)`/NUCterm$`Terminal Volume (nm^3)`,'Area' <- 'Nucleus Accumbens')
-vpdf <- data.frame('Mitochondrial Volume Fraction' <- VENterm$`Total Mito Volume (nm^3)`/VENterm$`Terminal Volume (nm^3)`,'Area' <- 'Ventral Pallidum')
-names(lhdf) <- c('Mitochondrial Volume Fraction','Area')
-names(nudf) <- c('Mitochondrial Volume Fraction','Area')
-names(vpdf) <- c('Mitochondrial Volume Fraction','Area')
-
-mddf = rbind(lhdf,nudf,vpdf)
-pdf('Mitos_in_Boutons2.pdf',width=5, height=4)
-ggplot(mddf, aes(x=mddf$`Mitochondrial Volume Fraction`, fill=mddf$Area))+ 
-  geom_density(alpha=.2) +
-  xlim(0,.5) + xlab("Mitochondrial Volume Ratio") + ylab("Distribution") +
-  labs(fill = "Brain Area") +
-  ggtitle("Mitochondrial Volume Fraction in Boutons")
-dev.off()
-
-## Mito Vol fraction vs terminal size
-mfac <- combdf
-p10 <- ggplot(mfac, aes(x=mfac$`Terminal Size`*10^-9,y=mfac$`Miotchondrial Volume Faction`))+geom_point()
-
-#AZ Distros
-LHBves$`Area` <- 'Lateral Habenula'
-NUCves$`Area` <- 'Nucleus Accumbens'
-VENves$`Area` <- 'Ventral Pallidum'
-
-vesAZ <- rbind(LHBves,NUCves,VENves)
-
-p11 <- ggplot(vesAZ, aes(x=vesAZ$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`, 
-                  color=vesAZ$`Type - Whether vesicle is miniSOG labeled or canonical`)) +
-  geom_density()
-
-
-
-## Subtyping Plot
-
-aind <- combdf$`Post-synaptic Element` =='Dendrite' | combdf$`Post-synaptic Element` =='Spine' | combdf$`Post-synaptic Element` =='Cell Body'
-aind <- replace(aind,is.na(aind),FALSE)
-atydf <- combdf[aind,]
-bind <- atydf$`Synapse Type` == 'AS' | atydf$`Synapse Type` == 'S' | atydf$Area == 'Nucleus Accumbens'
-subdat <- atydf[bind,]
-#subdat[subdat$Area=='Nucleus Accumbens',]$`Synapse Type` <- 'En Passant'
-#subdat$`Synapse Type` <- factor(subdat$`Synapse Type`, levels = c("AS", "S", "En Passant"))
-
-# two boutons in the NUCACC data are in fact terminal
-#subdat[subdat$Area=='Nucleus Accumbens' & subdat$ID == 92,]$`Synapse Type` = 'S'
-#subdat[subdat$Area=='Nucleus Accumbens' & subdat$ID == 7,]$`Synapse Type` = 'AS'
-
-pal1 = c("#CE1DE2", "#19e6df","#f2be47")
-  
-pdf("SubClassesData4.pdf",width = 7, height = 5)
-p12 <- ggplot(subdat, aes(x=subdat$`Vesicle Count`, y=subdat$`Terminal Size`*10^-9,col=subdat$`Synapse Type`)) +
-  geom_point(aes(shape=subdat$`Post-synaptic Element`),alpha=.8,size=3) +
-  scale_y_log10() +
-  scale_x_log10() +
-  facet_grid(. ~ Area)+ 
-  scale_color_manual(values = pal1,labels=c("Asymmetric","Symmetric","En Passant")) +
-  xlab('Vesicle Counts per Bouton') +
-  #ylab(expression(Terminal~Size~(??m^3))) +
-  ylab(~ "Terminal Size " (mu*m^3)) +
-  labs(shape="Post-synaptic Element",color="Synapse Type") +
-  ggtitle("Synapse Characteristics by Targets, Types, and Sizes")+
-  guides(color=guide_legend(override.aes=list(shape=15,size=5.6,alpha=.7)))
-p12
-dev.off()
-
-
-
-## Ves Mean per brain area
-for (i in NF$Terminal_ID){
-  vsp <- VENves[VENves$`Terminal ID - which terminal the vesicle is in` ==i,]
-}
-
-
-
-# Mean data comparisons
-mean(combdf[combdf$`Post-synaptic Element`=='Cell Body',]$`Vesicle Count`)
-mean(combdf[combdf$`Post-synaptic Element`!='Cell Body',]$`Vesicle Count`)
-
-mean(combdf[combdf$Area=='Lateral Habenula',]$`Vesicle Count`)
-mean(combdf[combdf$Area!='Lateral Habenula',]$`Vesicle Count`)
-
-mean(combdf[combdf$Area=='Lateral Habenula',]$`Vesicle Cloud Density`)
-mean(combdf[combdf$Area!='Lateral Habenula',]$`Vesicle Cloud Density`)
-
-
-
-mean(combdf[combdf$Area=='Nucleus Accumbens',]$`Vesicle Count`)
-mean(combdf[combdf$Area!='Nucleus Accumbens',]$`Vesicle Count`)
-
-mean(combdf[combdf$Area=='Nucleus Accumbens',]$`Vesicle Cloud Density`)
-mean(combdf[combdf$Area!='Nucleus Accumbens',]$`Vesicle Cloud Density`)
-
-mean(combdf[combdf$`Post-synaptic Element`=='Spine',]$`Vesicle Cloud Density`)
-mean(combdf[combdf$`Post-synaptic Element`!='Spine',]$`Vesicle Cloud Density`)
-
-
-
-
-
-
-
-
-
+setwd("~/Neuron_Rush_Sep/oct_more")
+require('readxl')
+require('ggplot2')
+require('plyr')
+require('gridExtra')
+require('ggpubr')
+require('cowplot')
+require('wesanderson')
+
+# import data from 3 brain areas
+# synaptic vesicle data
+LHBves = read_excel("Lateral_Habenula_VesicleData.xls")
+NUCves = read_excel("Nucleas_Accumbens_VesicleData_re2.xls")
+VENves = read_excel("Ventral_Palladum_VesicleData.xls")
+  
+# bouton data
+LHBterm = read_excel("Lateral_Habenula_T_Summary_Data.xls")
+NUCterm <- read_excel("Nucleas_Accumbens_T_Summary_Data_re2.xls")
+VENterm <- read_excel("Ventral_Palladum_T_Summary_Data.xls")
+
+# qualitative analysis data
+NUCType <- read_excel("Summary_Boutons_3Areas_AZneeded.xlsx")
+LHBType <- read_excel("Summary_Boutons_3Areas_AZneeded.xlsx",sheet = 2)
+VENType <- read_excel("Summary_Boutons_3Areas_AZneeded.xlsx",sheet = 3)
+
+NUCType$`Bouton ID`<-as.numeric(substring(NUCType$`Bouton ID`, 2))
+LHBType$`Bouton ID`<-as.numeric(substring(LHBType$`Bouton ID`, 2))
+VENType$`Bouton ID`<-as.numeric(substring(VENType$`Bouton ID`, 2))
+
+NUCAuto <- read_excel("Nucleas_Accumbens_AutoBoutonData.xls")
+
+## Reset Accumbens with Auto Bouton Data
+reNUC <- NUCType
+uids <- unique(NUCAuto$`Terminal ID in AutoBouton Labels`)
+addData <- data.frame(matrix(data=NA,nrow=length(uids)-nrow(reNUC),ncol = ncol(reNUC)))
+names(addData) <- names(reNUC)
+reNUC <- rbind(reNUC,addData)
+reNUC$`Bouton ID` <- uids
+reNUC$`Bouton Type` <- NA
+for (i in 1:length(reNUC$`Bouton ID`)){
+  iddx <- reNUC$`Bouton ID`[i]
+  idens <- NUCAuto[NUCAuto$`Terminal ID in AutoBouton Labels`==iddx,]
+  idens <- idens[order(idens$nVoxels),]
+  idens
+  
+  chk <- idens[1,2]
+  if (chk %in% c(10, 9 ,4)){chk <- idens[2,2]}
+  if (is.na(chk)){
+    reNUC$`Post-synaptic element`[i] <- "?"
+    reNUC$`Type of Synapse`[i] <- "?"
+    reNUC$`Bouton Type` <- "En passant"
+    next
+  }
+  if (chk == 5) {
+    reNUC$`Post-synaptic element`[i] <- "Dendrite"
+    reNUC$`Type of Synapse`[i] <- "S"
+    reNUC$`Bouton Type` <- "S"
+  }
+  if (chk==1) {
+    reNUC$`Post-synaptic element`[i] <- "Dendrite"
+    reNUC$`Type of Synapse`[i] <- "S"
+    reNUC$`Bouton Type` <- "S"
+  }  
+  if (chk==2) {
+    reNUC$`Post-synaptic element`[i] <- "Dendrite"
+    reNUC$`Type of Synapse`[i] <- "AS"
+    reNUC$`Bouton Type` <- "Terminal"
+  }  
+  if (chk==3) {
+    reNUC$`Post-synaptic element`[i] <- "Spine"
+    reNUC$`Type of Synapse`[i] <- "S"
+    reNUC$`Bouton Type` <- "S"
+  }  
+  if (chk==6) {
+    reNUC$`Post-synaptic element`[i] <- "Spine"
+    reNUC$`Type of Synapse`[i] <- "AS"
+    reNUC$`Bouton Type` <- "AS"
+  }  
+  if (chk==7) {
+    reNUC$`Post-synaptic element`[i] <- "Dendrite"
+    reNUC$`Type of Synapse`[i] <- "AS"
+    reNUC$`Bouton Type` <- "AS"
+  }  
+  if (chk==8) {
+    reNUC$`Post-synaptic element`[i] <- "Spine"
+    reNUC$`Type of Synapse`[i] <- "AS"
+    reNUC$`Bouton Type` <- "AS"
+  }  
+  if (chk==11) {
+    reNUC$`Post-synaptic element`[i] <- "?"
+    reNUC$`Type of Synapse`[i] <- "?"
+    reNUC$`Bouton Type` <- "En passant"
+  } 
+}
+NUCType <- reNUC
+
+## Vesicle Vol Fractions
+#NUC
+vesNUC <- data.frame(matrix(ncol = 9, nrow = 0))
+names(vesNUC) <- c('Vesicular Volume Fraction','Miotchondrial Volume Faction','Area',
+                   'Synapse Type','Post-synaptic Element','Vesicle Count', 'Vesicle Cloud Density','ID','Terminal Size')
+a = 1
+for (i in 1:length(NUCType$`Bouton ID`)){
+  if (!(NUCType$`Bouton ID`[i] %in% NUCterm$`Terminal ID`)){
+    next
+  }
+  vs <- sum((4/3)*(NUCves[NUCves$`Terminal ID - which terminal the vesicle is in` ==NUCType$`Bouton ID`[i],]$`Size(nm) - represented as spherical radius`)^3)
+  vs = vs / NUCterm[NUCterm$`Terminal ID`==NUCType$`Bouton ID`[i],]$`Terminal Volume (nm^3)`
+  mf = NUCterm[NUCterm$`Terminal ID`==NUCType$`Bouton ID`[i],]$`Total Mito Volume (nm^3)` /NUCterm[NUCterm$`Terminal ID`==NUCType$`Bouton ID`[i],]$`Terminal Volume (nm^3)`
+  ty = NUCType[NUCType$`Bouton ID` == NUCType$`Bouton ID`[i],]$`Type of Synapse`
+  pe = NUCType[NUCType$`Bouton ID` == NUCType$`Bouton ID`[i],]$`Post-synaptic element`
+  vesNUC[a,]$`Vesicular Volume Fraction` <- vs
+  vesNUC[a,]$`Miotchondrial Volume Faction` <- mf
+  vesNUC[a,]$`Area` <- 'Nucleus Accumbens'
+  vesNUC[a,]$`Synapse Type` <- ty[1]
+  vesNUC[a,]$`Post-synaptic Element` <- pe[1]
+  vesNUC[a,]$ID <- NUCType$`Bouton ID`[i]
+  vesNUC[a,]$`Vesicle Count`<- nrow(NUCves[NUCves$`Terminal ID - which terminal the vesicle is in` == NUCType$`Bouton ID`[i],])
+  vesNUC[a,]$`Vesicle Cloud Density` <- vesNUC[a,]$`Vesicle Count` / ((NUCterm[NUCterm$`Terminal ID`==NUCType$`Bouton ID`[i],]$`Terminal Volume (nm^3)` -
+                                                                         NUCterm[NUCterm$`Terminal ID`==NUCType$`Bouton ID`[i],]$`Total Mito Volume (nm^3)`)*10^-9 )
+  vesNUC[a,]$`Terminal Size` <- NUCterm[NUCterm$`Terminal ID`==NUCType$`Bouton ID`[i],]$`Terminal Volume (nm^3)`
+  #vesNUC[a,]$`Bouton Type` <- NUCType$`Bouton Type`[i]
+  
+  
+  a = a+1
+}
+#LHB
+vesLHB <- data.frame(matrix(ncol = 9, nrow = 0))
+names(vesLHB) <- c('Vesicular Volume Fraction','Miotchondrial Volume Faction','Area',
+                   'Synapse Type','Post-synaptic Element','Vesicle Count', 'Vesicle Cloud Density','ID','Terminal Size')
+a = 1
+for (i in 1:length(LHBType$`Bouton ID`)){
+  if (!(LHBType$`Bouton ID`[i] %in% LHBterm$`Terminal ID`)){
+    next
+  }
+  vs <- sum((4/3)*(LHBves[LHBves$`Terminal ID - which terminal the vesicle is in` ==LHBType$`Bouton ID`[i],]$`Size(nm) - represented as spherical radius`)^3)
+  vs = vs / LHBterm[LHBterm$`Terminal ID`==LHBType$`Bouton ID`[i],]$`Terminal Volume (nm^3)`
+  mf = LHBterm[LHBterm$`Terminal ID`==LHBType$`Bouton ID`[i],]$`Total Mito Volume (nm^3)` /LHBterm[LHBterm$`Terminal ID`==LHBType$`Bouton ID`[i],]$`Terminal Volume (nm^3)`
+  ty = LHBType[LHBType$`Bouton ID` == LHBType$`Bouton ID`[i],]$`Type of Synapse`
+  pe = LHBType[LHBType$`Bouton ID` == LHBType$`Bouton ID`[i],]$`Post-synaptic element`
+  vesLHB[a,]$`Vesicular Volume Fraction` <- vs[1]
+  vesLHB[a,]$`Miotchondrial Volume Faction` <- mf[1]
+  vesLHB[a,]$`Area` <- 'Lateral Habenula'
+  vesLHB[a,]$`Synapse Type` <- ty
+  vesLHB[a,]$`Post-synaptic Element` <- pe
+  vesLHB[a,]$ID <- LHBType$`Bouton ID`[i]
+  vesLHB[a,]$`Vesicle Count`<- nrow(LHBves[LHBves$`Terminal ID - which terminal the vesicle is in` == LHBType$`Bouton ID`[i],])
+  vesLHB[a,]$`Vesicle Cloud Density` <- vesLHB[a,]$`Vesicle Count` / ((LHBterm[LHBterm$`Terminal ID`==LHBType$`Bouton ID`[i],][1,1]$`Terminal Volume (nm^3)` -
+                                                                        LHBterm[LHBterm$`Terminal ID`==LHBType$`Bouton ID`[i],]$`Total Mito Volume (nm^3)`[1])*10^-9 )
+  vesLHB[a,]$`Terminal Size` <- LHBterm[LHBterm$`Terminal ID`==LHBType$`Bouton ID`[i],][1,1]$`Terminal Volume (nm^3)`
+  
+  
+  
+  a = a+1
+}
+
+#VEN
+vesVEN <- data.frame(matrix(ncol = 9, nrow = 0))
+names(vesVEN) <- c('Vesicular Volume Fraction','Miotchondrial Volume Faction','Area',
+                   'Synapse Type','Post-synaptic Element','Vesicle Count', 'Vesicle Cloud Density','ID','Terminal Size')
+a = 1
+for (i in 1:length(VENType$`Bouton ID`)){
+  if (!(VENType$`Bouton ID`[i] %in% VENterm$`Terminal ID`)){
+    next
+  }
+  vs <- sum((4/3)*(VENves[VENves$`Terminal ID - which terminal the vesicle is in` ==VENType$`Bouton ID`[i],]$`Size(nm) - represented as spherical radius`)^3)
+  vs = vs / VENterm[VENterm$`Terminal ID`==VENType$`Bouton ID`[i],]$`Terminal Volume (nm^3)`
+  mf = VENterm[VENterm$`Terminal ID`==VENType$`Bouton ID`[i],]$`Total Mito Volume (nm^3)` /VENterm[VENterm$`Terminal ID`==VENType$`Bouton ID`[i],]$`Terminal Volume (nm^3)`
+  ty = VENType[VENType$`Bouton ID` == VENType$`Bouton ID`[i],]$`Type of Synapse`
+  pe = VENType[VENType$`Bouton ID` == VENType$`Bouton ID`[i],]$`Post-synaptic element`
+  vesVEN[a,]$`Vesicular Volume Fraction` <- vs
+  vesVEN[a,]$`Miotchondrial Volume Faction` <- mf
+  vesVEN[a,]$`Area` <- 'Ventral Pallidum'
+  vesVEN[a,]$`Synapse Type` <- ty
+  vesVEN[a,]$`Post-synaptic Element` <- pe
+  vesVEN[a,]$ID <- VENType$`Bouton ID`[i]
+  vesVEN[a,]$`Vesicle Count`<- nrow(VENves[VENves$`Terminal ID - which terminal the vesicle is in` == VENType$`Bouton ID`[i],])
+  vesVEN[a,]$`Vesicle Cloud Density` <- vesVEN[a,]$`Vesicle Count` / ((VENterm[VENterm$`Terminal ID`==VENType$`Bouton ID`[i],]$`Terminal Volume (nm^3)` -
+                                                                         VENterm[VENterm$`Terminal ID`==VENType$`Bouton ID`[i],]$`Total Mito Volume (nm^3)`)*10^-9 )
+  
+  vesVEN[a,]$`Terminal Size` <- VENterm[VENterm$`Terminal ID`==VENType$`Bouton ID`[i],]$`Terminal Volume (nm^3)`
+  
+  
+  a = a+1
+}
+
+
+
+combdf <- rbind(vesLHB,vesNUC,vesVEN)
+combdf <- na.omit(combdf)
+
+
+
+#thickness of lines around subplots
+sb = .2
+
+# 3plots for type of synapse plot ## SYMMETRIC VS ASYMMETRIC
+pal2 = c("#d6b629","#ff00a5","#002bff")
+pal1 = c("#CE1DE2", "#19e6df")
+
+tydf <- combdf[combdf$`Synapse Type` == 'AS' | combdf$`Synapse Type` == 'S',]
+mu <- ddply(tydf, "`Synapse Type`", summarise, grp.mean=mean(`Miotchondrial Volume Faction`))
+mu2 <- ddply(tydf, "`Synapse Type`", summarise, grp.mean=mean(`Vesicle Count`))
+mu3 <- ddply(tydf, "`Synapse Type`", summarise, grp.mean=mean(`Vesicle Cloud Density`))
+
+pdf('Synapse_Type_Multi5.pdf',width=16,height=14,onefile = TRUE)
+p1 <- ggplot(tydf, aes(x=tydf$`Miotchondrial Volume Faction`, fill=tydf$`Synapse Type`))+ 
+  geom_density(aes(x=tydf$`Miotchondrial Volume Faction`,y=..density..),alpha=.05) +
+  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.15,binwidth = .04) +
+  geom_vline(data=mu, aes(xintercept=grp.mean, color=mu$`Synapse Type`),
+             linetype="dashed",show.legend = FALSE) +
+  xlim(0,.45) + xlab("Mitochondrial Volume Fraction") + ylab("Density")+ 
+  ggtitle("Mitochondrial Volume Proportion of Boutons") +
+  theme(legend.position = "left",plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb)) +  labs(fill = "Synapse Type") +
+  scale_fill_manual(values=pal1, labels = c('Asymmetric','Symmetric')) + 
+  scale_color_manual(values = pal1)
+  #scale_fill_discrete(labels= c('Asymmetric','Symmetric'), values = pal1)
+
+## faceted vesicle count + vesicle cloud density + mito frac
+p2 <- ggplot(tydf, aes(x=tydf$`Vesicle Count`, fill=tydf$`Synapse Type`))+ 
+  geom_density(aes(x=tydf$`Vesicle Count`,y=..density..),alpha=.05) +
+  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.15,binwidth = 250) +
+  geom_vline(data=mu2, aes(xintercept=grp.mean, color=mu$`Synapse Type`),
+             linetype="dashed",show.legend = FALSE) +
+  xlab("Number of Vesicles inside Terminal") + ylab("Density") +
+  labs(fill = "Synapse Type") +
+  ggtitle("Synaptic Vesicle Counts per Bouton") +
+  theme(plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb))+
+  scale_fill_manual(values=pal1, labels = c('Asymmetric','Symmetric')) +
+  guides(fill=FALSE)+ 
+  scale_color_manual(values = pal1)
+
+p3 <- ggplot(tydf, aes(x=tydf$`Vesicle Cloud Density`, fill=tydf$`Synapse Type`))+ 
+  geom_density(aes(x=tydf$`Vesicle Cloud Density`,y=..density..),alpha=.05) +
+  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.15,binwidth = 400) +
+  geom_vline(data=mu3, aes(xintercept=grp.mean, color=mu$`Synapse Type`),
+             linetype="dashed",show.legend = FALSE) +
+  xlab(expression(Vesicle~Count~Divided~by~Terminal~Volume~(N[vesicles]/??m^3))) +
+  ylab("Density") +
+  xlim(300,NA)+
+  labs(fill = "Synapse Type") +
+  ggtitle("Vesicle Cloud Solidity") +
+  theme(plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb))+
+  scale_fill_manual(values=pal1, labels = c('Asymmetric','Symmetric')) +
+  guides(fill=FALSE)+ 
+  scale_color_manual(values = pal1)
+
+
+## 3plots for type of synapse plot ## TARGET
+
+aind <- combdf$`Post-synaptic Element` =='Dendrite' | combdf$`Post-synaptic Element` =='Spine' | combdf$`Post-synaptic Element` =='Cell Body'
+aind <- replace(aind,is.na(aind),FALSE)
+atydf <- combdf[aind,]
+amu <- ddply(tydf, "`Post-synaptic Element`", summarise, grp.mean=mean(`Miotchondrial Volume Faction`))
+amu2 <- ddply(tydf, "`Post-synaptic Element`", summarise, grp.mean=mean(`Vesicle Count`))
+amu3 <- ddply(tydf, "`Post-synaptic Element`", summarise, grp.mean=mean(`Vesicle Cloud Density`))
+
+#pdf('testpostsyn.pdf')
+p4 <- ggplot(atydf, aes(x=atydf$`Miotchondrial Volume Faction`, fill=atydf$`Post-synaptic Element`))+ 
+  geom_density(aes(x=atydf$`Miotchondrial Volume Faction`,y=..density..),alpha=.2) +
+  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.3,binwidth = .03) +
+  geom_vline(data=amu, aes(xintercept=grp.mean, color=amu$`Post-synaptic Element`),
+             linetype="dashed",show.legend = FALSE) +
+  xlim(0,.45) + xlab("Mitochondrial Volume Fraction") + ylab("Density")+ 
+  #ggtitle("Mitochondrial Volume Porportion of Boutons") +
+  theme(legend.position = "left",plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb)) +  
+  labs(fill = "Post-synaptic Element") +#+
+  scale_fill_manual(values=pal2)+ 
+  scale_color_manual(values = pal2)
+#p4
+#dev.off()
+
+## faceted vesicle count + vesicle cloud density + mito frac
+p5 <- ggplot(atydf, aes(x=atydf$`Vesicle Count`, fill=atydf$`Post-synaptic Element`))+ 
+  geom_density(aes(x=atydf$`Vesicle Count`,y=..density..),alpha=.2) +
+  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.3,binwidth = 250) +
+  geom_vline(data=amu2, aes(xintercept=grp.mean, color=amu2$`Post-synaptic Element`),
+             linetype="dashed",show.legend = FALSE) +
+  xlab("Number of Vesicles inside Terminal") + ylab("Density") +
+  labs(fill = "Post-synaptic Element") +
+  scale_fill_manual(values=pal2) +
+  theme(plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb))+
+  guides(fill=FALSE)+ 
+  scale_color_manual(values = pal2)
+
+p6 <- ggplot(atydf, aes(x=atydf$`Vesicle Cloud Density`, fill=atydf$`Post-synaptic Element`))+ 
+  geom_density(aes(x=atydf$`Vesicle Cloud Density`,y=..density..),alpha=.2) +
+  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.3,binwidth = 350) +
+  geom_vline(data=amu3, aes(xintercept=grp.mean, color=amu3$`Post-synaptic Element`),
+             linetype="dashed",show.legend = FALSE) +
+  xlab(expression(Vesicle~Count~Divided~by~Terminal~Volume~(N[vesicles]/??m^3))) +
+  ylab("Density") +
+  xlim(300,3200)+
+  labs(fill = "Post-synaptic Element") +
+  scale_fill_manual(values=pal2) +
+  #ggtitle("Vesicle Cloud Solidity") +
+  theme(plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb))+
+  guides(fill=FALSE)+ 
+  scale_color_manual(values = pal2)
+
+
+## 3 Plots for AREA  ######## 
+
+
+btydf <- combdf
+bmu <- ddply(tydf, "`Area`", summarise, grp.mean=mean(`Miotchondrial Volume Faction`))
+bmu2 <- ddply(tydf, "`Area`", summarise, grp.mean=mean(`Vesicle Count`))
+bmu3 <- ddply(tydf, "`Area`", summarise, grp.mean=mean(`Vesicle Cloud Density`))
+
+#pdf('testpostsyn.pdf')
+p7 <- ggplot(btydf, aes(x=btydf$`Miotchondrial Volume Faction`, fill=btydf$`Area`))+ 
+  geom_density(aes(x=btydf$`Miotchondrial Volume Faction`,y=..density..),alpha=.2) +
+  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.3,binwidth = .03) +
+  geom_vline(data=bmu, aes(xintercept=grp.mean, color=bmu$`Area`),
+             linetype="dashed",show.legend = FALSE) +
+  xlim(0,.45) + xlab("Mitochondrial Volume Fraction") + ylab("Density")+ 
+  #ggtitle("Mitochondrial Volume Porportion of Boutons") +
+  theme(legend.position = "left",plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb)) +  
+  labs(fill = "Area") #+#+
+  #scale_fill_manual(values=pal3)+ 
+  #scale_color_manual(values = pal3)
+#p4
+#dev.off()
+
+## faceted vesicle count + vesicle cloud density + mito frac
+p8 <- ggplot(btydf, aes(x=btydf$`Vesicle Count`, fill=btydf$`Area`))+ 
+  geom_density(aes(x=btydf$`Vesicle Count`,y=..density..),alpha=.2) +
+  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.3,binwidth = 250) +
+  geom_vline(data=bmu2, aes(xintercept=grp.mean, color=bmu2$`Area`),
+             linetype="dashed",show.legend = FALSE) +
+  xlab("Number of Vesicles inside Terminal") + ylab("Density") +
+  labs(fill = "Area") +
+  #scale_fill_manual(values=pal3) +
+  theme(plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb))+
+  guides(fill=FALSE)#+ 
+  #scale_color_manual(values = pal3)
+
+p9 <- ggplot(btydf, aes(x=btydf$`Vesicle Cloud Density`, fill=btydf$`Area`))+ 
+  geom_density(aes(x=btydf$`Vesicle Cloud Density`,y=..density..),alpha=.2) +
+  geom_histogram(aes(y=..density..),position="identity",colour="#363636", alpha=0.3,binwidth = 350) +
+  geom_vline(data=bmu3, aes(xintercept=grp.mean, color=bmu3$`Area`),
+             linetype="dashed",show.legend = FALSE) +
+  xlab(expression(Vesicle~Count~Divided~by~Terminal~Volume~(N[vesicles]/??m^3))) +
+  ylab("Density") +
+  xlim(300,3200)+
+  labs(fill = "Area") +
+  #scale_fill_manual(values=pal3) +
+  #ggtitle("Vesicle Cloud Solidity") +
+  theme(plot.title = element_text(hjust = 0.5),plot.background = element_rect(color = "gray",size=sb))+
+  guides(fill=FALSE)
+  #scale_color_manual(values = pal3)
+
+#grid.arrange(arrangeGrob(p1,p2,p3,ncol=3))
+plot_grid(p1,p2,p3,p4,p5,p6,p7,p8,p9,nrow = 3,ncol = 3,rel_widths = c(1-(.33+.29),.29,.33),labels="AUTO",label_size = 16)
+dev.off()
+
+#means and errors
+tydf <- combdf[combdf$`Synapse Type` == 'AS' | combdf$`Synapse Type` == 'S',]
+mu <- ddply(tydf, "`Synapse Type`", summarise, grp.mean=mean(`Miotchondrial Volume Faction`),grp.sd=sd(`Miotchondrial Volume Faction`))
+mu2 <- ddply(tydf, "`Synapse Type`", summarise, grp.mean=mean(`Vesicle Count`),grp.sd=sd(`Vesicle Count`))
+mu3 <- ddply(tydf, "`Synapse Type`", summarise, grp.mean=mean(`Vesicle Cloud Density`),grp.sd=sd(`Vesicle Cloud Density`))
+
+btydf <- combdf
+bmu <- ddply(tydf, "`Area`", summarise, grp.mean=mean(`Miotchondrial Volume Faction`),grp.sd=sd(`Miotchondrial Volume Faction`))
+bmu2 <- ddply(tydf, "`Area`", summarise, grp.mean=mean(`Vesicle Count`),grp.sd=sd(`Vesicle Count`))
+bmu3 <- ddply(tydf, "`Area`", summarise, grp.mean=mean(`Vesicle Cloud Density`),grp.sd=sd(`Vesicle Cloud Density`))
+
+aind <- combdf$`Post-synaptic Element` =='Dendrite' | combdf$`Post-synaptic Element` =='Spine' | combdf$`Post-synaptic Element` =='Cell Body'
+aind <- replace(aind,is.na(aind),FALSE)
+atydf <- combdf[aind,]
+amu <- ddply(tydf, "`Post-synaptic Element`", summarise, grp.mean=mean(`Miotchondrial Volume Faction`),grp.sd=sd(`Miotchondrial Volume Faction`))
+amu2 <- ddply(tydf, "`Post-synaptic Element`", summarise, grp.mean=mean(`Vesicle Count`),grp.sd=sd(`Vesicle Count`))
+amu3 <- ddply(tydf, "`Post-synaptic Element`", summarise, grp.mean=mean(`Vesicle Cloud Density`),grp.sd=sd(`Vesicle Cloud Density`))
+
+
+
+
+
+#pdf('Synapse_Type_Ves.pdf',width=5, height=4)
+ggplot(tydf, aes(x=tydf$`Vesicle Count` ,y=..scaled.., fill=tydf$`Synape Type`))+ 
+  geom_density(alpha=.2) +
+  xlim(0,NA) + xlab("Number of Vesicles per Terminal") + ylab("Density") +
+  labs(fill = "Synapse Type") +
+  ggtitle("Synaptic Vesicle Counts of Boutons")+
+  scale_fill_discrete(labels= c('Asymmetric','Symmetric'))+
+  xlim(NA,3500)
+#dev.off()
+
+pdf('Synapse_Type_Cloud2.pdf',width=3, height=3)
+ggplot(tydf, aes(x=tydf$`Vesicle Cloud Density` ,y=..scaled.., fill=tydf$`Synape Type`))+ 
+  geom_density(alpha=.2) +
+  xlim(0,NA) + 
+  xlab(expression(Vesicle~Count~Divided~by~Terminal~Volume~(N[vesicles]/??m[3]))) + 
+  ylab("Density") +
+  labs(fill = "Synapse Type") +
+  ggtitle("Vesicle Cloud Density by Synapse Type")+
+  scale_fill_discrete(labels= c('Asymmetric','Symmetric'))
+dev.off()
+
+
+
+## Mito Vol Fractions across Areas plot
+lhdf <- data.frame('Mitochondrial Volume Fraction' <- VENterm$`Total Mito Volume (nm^3)`/VENterm$`Terminal Volume (nm^3)`,'Area' <- 'Lateral Habenula')
+nudf <- data.frame('Mitochondrial Volume Fraction' <- NUCterm$`Total Mito Volume (nm^3)`/NUCterm$`Terminal Volume (nm^3)`,'Area' <- 'Nucleus Accumbens')
+vpdf <- data.frame('Mitochondrial Volume Fraction' <- VENterm$`Total Mito Volume (nm^3)`/VENterm$`Terminal Volume (nm^3)`,'Area' <- 'Ventral Pallidum')
+names(lhdf) <- c('Mitochondrial Volume Fraction','Area')
+names(nudf) <- c('Mitochondrial Volume Fraction','Area')
+names(vpdf) <- c('Mitochondrial Volume Fraction','Area')
+
+mddf = rbind(lhdf,nudf,vpdf)
+pdf('Mitos_in_Boutons2.pdf',width=5, height=4)
+ggplot(mddf, aes(x=mddf$`Mitochondrial Volume Fraction`, fill=mddf$Area))+ 
+  geom_density(alpha=.2) +
+  xlim(0,.5) + xlab("Mitochondrial Volume Ratio") + ylab("Distribution") +
+  labs(fill = "Brain Area") +
+  ggtitle("Mitochondrial Volume Fraction in Boutons")
+dev.off()
+
+## Mito Vol fraction vs terminal size
+mfac <- combdf
+p10 <- ggplot(mfac, aes(x=mfac$`Terminal Size`*10^-9,y=mfac$`Miotchondrial Volume Faction`))+geom_point()
+
+#AZ Distros
+LHBves$`Area` <- 'Lateral Habenula'
+NUCves$`Area` <- 'Nucleus Accumbens'
+VENves$`Area` <- 'Ventral Pallidum'
+
+vesAZ <- rbind(LHBves,NUCves,VENves)
+
+p11 <- ggplot(vesAZ, aes(x=vesAZ$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`, 
+                  color=vesAZ$`Type - Whether vesicle is miniSOG labeled or canonical`)) +
+  geom_density()
+
+
+
+## Subtyping Plot
+
+aind <- combdf$`Post-synaptic Element` =='Dendrite' | combdf$`Post-synaptic Element` =='Spine' | combdf$`Post-synaptic Element` =='Cell Body'
+aind <- replace(aind,is.na(aind),FALSE)
+atydf <- combdf[aind,]
+bind <- atydf$`Synapse Type` == 'AS' | atydf$`Synapse Type` == 'S' | atydf$Area == 'Nucleus Accumbens'
+subdat <- atydf[bind,]
+#subdat[subdat$Area=='Nucleus Accumbens',]$`Synapse Type` <- 'En Passant'
+#subdat$`Synapse Type` <- factor(subdat$`Synapse Type`, levels = c("AS", "S", "En Passant"))
+
+# two boutons in the NUCACC data are in fact terminal
+#subdat[subdat$Area=='Nucleus Accumbens' & subdat$ID == 92,]$`Synapse Type` = 'S'
+#subdat[subdat$Area=='Nucleus Accumbens' & subdat$ID == 7,]$`Synapse Type` = 'AS'
+
+pal1 = c("#CE1DE2", "#19e6df","#f2be47")
+  
+pdf("SubClassesData4.pdf",width = 7, height = 5)
+p12 <- ggplot(subdat, aes(x=subdat$`Vesicle Count`, y=subdat$`Terminal Size`*10^-9,col=subdat$`Synapse Type`)) +
+  geom_point(aes(shape=subdat$`Post-synaptic Element`),alpha=.8,size=3) +
+  scale_y_log10() +
+  scale_x_log10() +
+  facet_grid(. ~ Area)+ 
+  scale_color_manual(values = pal1,labels=c("Asymmetric","Symmetric","En Passant")) +
+  xlab('Vesicle Counts per Bouton') +
+  #ylab(expression(Terminal~Size~(??m^3))) +
+  ylab(~ "Terminal Size " (mu*m^3)) +
+  labs(shape="Post-synaptic Element",color="Synapse Type") +
+  ggtitle("Synapse Characteristics by Targets, Types, and Sizes")+
+  guides(color=guide_legend(override.aes=list(shape=15,size=5.6,alpha=.7)))
+p12
+dev.off()
+
+
+
+## Ves Mean per brain area
+for (i in NF$Terminal_ID){
+  vsp <- VENves[VENves$`Terminal ID - which terminal the vesicle is in` ==i,]
+}
+
+
+
+# Mean data comparisons
+mean(combdf[combdf$`Post-synaptic Element`=='Cell Body',]$`Vesicle Count`)
+mean(combdf[combdf$`Post-synaptic Element`!='Cell Body',]$`Vesicle Count`)
+
+mean(combdf[combdf$Area=='Lateral Habenula',]$`Vesicle Count`)
+mean(combdf[combdf$Area!='Lateral Habenula',]$`Vesicle Count`)
+
+mean(combdf[combdf$Area=='Lateral Habenula',]$`Vesicle Cloud Density`)
+mean(combdf[combdf$Area!='Lateral Habenula',]$`Vesicle Cloud Density`)
+
+
+
+mean(combdf[combdf$Area=='Nucleus Accumbens',]$`Vesicle Count`)
+mean(combdf[combdf$Area!='Nucleus Accumbens',]$`Vesicle Count`)
+
+mean(combdf[combdf$Area=='Nucleus Accumbens',]$`Vesicle Cloud Density`)
+mean(combdf[combdf$Area!='Nucleus Accumbens',]$`Vesicle Cloud Density`)
+
+mean(combdf[combdf$`Post-synaptic Element`=='Spine',]$`Vesicle Cloud Density`)
+mean(combdf[combdf$`Post-synaptic Element`!='Spine',]$`Vesicle Cloud Density`)
+
+
+library("ggplot2")
+library("wesanderson")
+library("readxl")
+library('reshape')
+library('plyr')
+library(scales)
+setwd('D:/Matthew/Neuron_Rush_Sep/Plots')
+source('multiplot.R')
+#lathab_vdata <- read_excel("Neuron_Rush_Sep/Vesicle_Data_Final.xls", 
+#                           sheet = "Lateral_Habenula_Vesicle Data")
+#nuccacc_vdata <- read_excel("Neuron_Rush_Sep/Vesicle_Data_Final.xls", 
+#                            sheet = "Nucleas_Accumbuns_Vesicle_Data")
+#venpal_vdata <- read_excel("Neuron_Rush_Sep/Vesicle_Data_Final.xls", 
+#                           sheet = "Ventral_Palladum_Vesicle_Data")
+
+#sizedata <- data.frame(rbind(as.factor(lathab_vdata$`Size(nm) - represented as spherical radius`),
+#                             as.factor(venpal_vdata$`Size(nm) - represented as spherical radius`),
+#                             as.factor(lathab_vdata$`Size(nm) - represented as spherical radius`)),
+#                       rbind(rep("Lateral Habenula",n=nrow(lathab_vdata))),
+#                       rbind(rep("Nucleas Accumbens",n=nrow(nuccacc_vdata))),
+#                       rbind(rep("Ventral Palladum",n=nrow(venpal_vdata))))
+
+## Vesicle Sizes by Vesicle Type & Sample
+pdf('typeareasize_Revised2.pdf',width=9,height=11)
+size_t <- data.frame(sizes = c(lhab_vd$`Size(nm) - represented as spherical radius`,
+                               nacc_vd$`Size(nm) - represented as spherical radius`,
+                               vpal_vd$`Size(nm) - represented as spherical radius`),
+                     sample = c(rep("Lateral Habenula", nrow(lhab_vd)),
+                                rep("Nucleus Accumbens", nrow(nacc_vd)),
+                                rep("Ventral Pallidum", nrow(vpal_vd))),
+                     type = c(lhab_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                              nacc_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                              vpal_vd$`Type - Whether vesicle is miniSOG labeled or canonical`))
+size_t$type <- as.character(size_t$type)
+size_t[size_t$type == 'Canonical',3] = rep('Unlabeled',length(size_t[size_t$type == 'Canonical',1]))
+size_t$type <- as.factor(size_t$type)
+size_t$sizes <- size_t$sizes*2
+size_t$sampletype <- as.factor(paste(size_t$sample, size_t$type,sep = ' '))
+size_t <- size_t[order(size_t$type),]
+size_t$sampletype <- factor(size_t$sampletype, levels = c("Lateral Habenula miniSOG", "Nucleus Accumbens miniSOG", "Ventral Pallidum miniSOG",
+                                                          "Lateral Habenula Unlabeled", "Nucleus Accumbens Unlabeled","Ventral Pallidum Unlabeled"))
+#size_t = na.omit(size_t)
+palte <- wes_palette(4, name = "GrandBudapest1")
+pt2 <- wes_palette(4, name = "GrandBudapest1")
+pt3 <- wes_palette(4, name = "GrandBudapest2")
+pt4 <- wes_palette(4, name = "Cavalcanti1")
+palte <- c(pt2[2],'#ba4477',pt2[4],pt3[4],pt4[4],pt3[2])
+tp <- ggplot(size_t, aes(x=sampletype, y=sizes, fill=sampletype)) +
+  geom_violin(trim=FALSE,scale = "width", width = .7,lwd=.38,bw = 2.75)+
+  scale_fill_manual(values = palte) +
+  geom_boxplot(width=0.1, fill="white",outlier.shape = NA)+
+  labs(title="Vesicle Sizes by Area and Type",x="Sample", y = "Vesicle Diameter (nm)") +
+  theme(#panel.background = element_rect(fill = "white",
+        #                                colour = "white",
+        #                                size = 0.5, linetype = "solid"),
+        #panel.grid.major = element_line(size = 0.5, linetype = 'solid',
+        #                                colour = "grey"),
+        #panel.grid.minor = element_line(size = 0.25, linetype = 'solid',
+        #                                colour = "white"),
+        axis.text.y=element_text(size=25),
+        axis.title.y=element_text(size=40,margin=margin(0,15,0,0)),
+        axis.title.x=element_blank(),
+        axis.text.x=element_blank(),
+        legend.title=element_blank(),
+        legend.text=element_text(size=22,margin=margin(0,0,0,3)),
+        plot.title = element_text(color="Black", size=40,hjust = 0.5,margin=margin(0,30,30,0)),
+        legend.position = c(.70, .91),
+        legend.background = element_rect(colour = 'black', fill = 'white', linetype='solid'),
+        legend.key.size = unit(1.6, 'lines')) +
+        scale_y_continuous(breaks = c(30,40,50,60,70,80,90), limits = c(25,100))
+tp
+dev.off()
+
+
+#Vesicles AZ vs Size 4 plot
+pdf('az_and_size_revised2.pdf',width=9,height=11)
+size_az <- data.frame(sizes = c(2*lhab_vd$`Size(nm) - represented as spherical radius`,
+                               2*nacc_vd$`Size(nm) - represented as spherical radius`,
+                               2*vpal_vd$`Size(nm) - represented as spherical radius`),
+                     sample = c(rep("Lateral Habenula", nrow(lhab_vd)),
+                                rep("Nucleus Accumbens", nrow(nacc_vd)),
+                                rep("Ventral Pallidum", nrow(vpal_vd))),
+                     type = c(lhab_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                              nacc_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                              vpal_vd$`Type - Whether vesicle is miniSOG labeled or canonical`),
+                     azdis = c(lhab_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`,
+                               nacc_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`,
+                               vpal_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`))
+
+palte = c(pt2[2],pt4[4],pt3[4])
+p4<-ggplot(size_az, aes(x=sizes, y=azdis,color = sample)) + geom_point(size = .1)+
+  labs(title="All Areas",x="Vesicle Diameter(nm)", y = "Distance to Active Zone (nm)") +
+  guides(colour = guide_legend(override.aes = list(size=7))) +
+  theme(plot.title = element_text(color="Black", size=22,hjust = 0.5),
+                                  legend.title=element_blank(),
+        legend.position = c(.8, .90),
+                                  axis.title.y=element_text(size=20,margin=margin(0,5,0,0)),
+                                  axis.title.x=element_text(size=20,margin=margin(5,0,0,0)),
+        legend.background = element_rect(colour = 'black', fill = 'white', linetype='solid'))
+
+
+#By Sample
+hda <- size_az[size_az$sample == 'Lateral Habenula',]
+naa <- size_az[size_az$sample == 'Nucleus Accumbens',]
+vpa <- size_az[size_az$sample == 'Ventral Pallidum',]
+p1<- ggplot(hda, aes(x=sizes, y=azdis)) + geom_point(size = .04)+
+  labs(title="Lateral Habenula",x="Vesicle Diameter(nm)", y = "Distance to Active Zone (nm)") +
+  theme(plot.title = element_text(color="Black", size=22,hjust = 0.5),
+        legend.title=element_blank(),
+        axis.title.y=element_text(size=20,margin=margin(0,5,0,0)),
+        axis.title.x=element_text(size=20,margin=margin(5,0,0,0)))
+p2<- ggplot(naa, aes(x=sizes, y=azdis)) + geom_point(size = .3)+
+  labs(title="Nucleus Accumbens",x="Vesicle Diameter(nm)", y = "Distance to Active Zone (nm)") +
+  theme(plot.title = element_text(color="Black", size=22,hjust = 0.5),
+        legend.title=element_blank(),
+        axis.title.y=element_text(size=20,margin=margin(0,5,0,0)),
+        axis.title.x=element_text(size=20,margin=margin(5,0,0,0)))
+p3<- ggplot(vpa, aes(x=sizes, y=azdis)) + geom_point(size = .3)+
+  labs(title="Ventral Pallidum",x="Vesicle Diameter(nm)", y = "Distance to Active Zone (nm)") +
+  theme(plot.title = element_text(color="Black", size=22,hjust = 0.5),
+        legend.title=element_blank(),
+        axis.title.y=element_text(size=20,margin=margin(0,5,0,0)),
+        axis.title.x=element_text(size=20,margin=margin(5,0,0,0)))
+
+multiplot(p1, p2, p3, p4, cols=2)
+dev.off()
+
+# Summary Plot Terminals Volume, Mito Volume, Vesicle Counts
+size_az <- data.frame(sizes = c(2*lhab_vd$`Size(nm) - represented as spherical radius`,
+                                2*nacc_vd$`Size(nm) - represented as spherical radius`,
+                                2*vpal_vd$`Size(nm) - represented as spherical radius`),
+                      sample = c(rep("Lateral Habenula", nrow(lhab_vd)),
+                                 rep("Nucleus Accumbens", nrow(nacc_vd)),
+                                 rep("Ventral Pallidum", nrow(vpal_vd))),
+                      type = c(lhab_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                               nacc_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                               vpal_vd$`Type - Whether vesicle is miniSOG labeled or canonical`),
+                      azdis = c(lhab_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`,
+                                nacc_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`,
+                                vpal_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`),
+                      iterm = c(lhab_vd$`Terminal ID - which terminal the vesicle is in`,
+                                nacc_vd$`Terminal ID - which terminal the vesicle is in`,
+                                vpal_vd$`Terminal ID - which terminal the vesicle is in`))
+hda <- size_az[size_az$sample == 'Lateral Habenula',]
+naa <- size_az[size_az$sample == 'Nucleus Accumbens',]
+vpa <- size_az[size_az$sample == 'Ventral Pallidum',]
+T_Sum <- read_excel("D:/Matthew/Neuron_Rush_Sep/Vesicle_Data_Final.xls", 
+                          sheet = "Mito_Data")
+T_Sum$X__1 <- paste(T_Sum$Sample, T_Sum$`Terminal ID`,sep = " ")
+
+
+
+# Count Vesicles
+hda$typeterm <- paste(hda$iterm, hda$type, hda$sample)
+ak <- as.data.frame(table(hda$typeterm))
+ak$Term <- as.numeric(sapply(strsplit(as.character(ak$Var1), " "), "[[", 1))
+for(i in 1:nrow(T_Sum[T_Sum$Sample == 'Lateral Habenula',])){
+  cn = ak[ak$Term == T_Sum$`Terminal ID`[i],]
+  T_Sum[i,8] = cn$Freq[2]
+  T_Sum[i,9] = cn$Freq[1]
+  T_Sum[i,10] = i
+}
+naa$typeterm <- paste(naa$iterm, naa$type, naa$sample)
+ak <- as.data.frame(table(naa$typeterm))
+ak$Term <- as.numeric(sapply(strsplit(as.character(ak$Var1), " "), "[[", 1))
+for(i in 28+1:nrow(T_Sum[T_Sum$Sample == 'Nucleus Accumbens',])){
+  cn = ak[ak$Term == T_Sum$`Terminal ID`[i],]
+  T_Sum[i,8] = cn$Freq[2]
+  T_Sum[i,9] = cn$Freq[1]
+  T_Sum[i,10] = i
+}
+vpa$typeterm <- paste(vpa$iterm, vpa$type, vpa$sample)
+ak <- as.data.frame(table(vpa$typeterm))
+ak$Term <- as.numeric(sapply(strsplit(as.character(ak$Var1), " "), "[[", 1))
+for(i in 45+1:nrow(T_Sum[T_Sum$Sample == 'Ventral Palladum',])){
+  cn = ak[ak$Term == T_Sum$`Terminal ID`[i],]
+  T_Sum[i,8] = cn$Freq[2]
+  T_Sum[i,9] = cn$Freq[1]
+  T_Sum[i,10] = i
+}
+T_Sum <- na.omit(T_Sum)
+T_Sum[,11]<- paste(T_Sum$Sample,T_Sum$ResetIndex)
+#T_Sum$V11 <- as.factor(T_Sum$V11)
+#begin plot
+pdf('TermSummary_small.pdf',width=3,height=3)
+T_so <- T_Sum[order(T_Sum$Sample),]
+T_so$V9 <- T_so$V9
+T_so$V8 <- T_so$V8
+T_so$V11 <- as.factor(T_so$V11)
+T_n <- data.frame(T_so$V11, T_so$V8, T_so$Sample)
+T_n2 <- data.frame(T_so$V11, T_so$V9, T_so$Sample)
+T_n[,4] <- rep("miniSOG", nrow(T_n))
+T_n2[,4] <- rep("Unlabeled", nrow(T_n2))
+names(T_n2) <- names(T_n)
+T_N <- rbind(T_n,T_n2)
+#T_so$V11 <- as.factor(T_so$V11)
+ggplot(T_N, aes(x=T_so.V11, y=T_so.V8, color = T_so.Sample, shape = V4)) + geom_point(size = 4) +
+  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
+  scale_x_discrete(limits=T_so$V11) + scale_y_log10(breaks = c(10,25,50,75,100,150,200,250,300,400,500,700,1000,1250,2000,3000)) + #breaks=c(0,50,100,150,200,500,600,900,1500,4000)) 
+  geom_line(aes(group = T_so.V11)) + labs(title="Vesicle Counts",x="Terminal ID", y = "Number of Vesicles") +
+  theme(plot.title = element_text(color="Black", size=22,hjust = 0.5),
+        legend.title=element_blank(),
+        axis.title.y=element_text(size=20,margin=margin(0,5,0,0)),
+        axis.title.x=element_text(size=20,margin=margin(5,0,0,0))) +
+  labs(shape="Type of Vesicles", colour="Area")
+
+
+dev.off()
+
+
+
+
+# Ratio miniSOG
+pdf('miniSOGratio.pdf',width=11,height=9.5)
+T_so[,12] <- T_so$V8/(T_so$V8+T_so$V9)
+
+ggplot(T_so,aes(x = V11,y = V12,fill = Sample))+geom_col() +
+  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
+  labs(title="miniSOG Vesicle Ratios",x="Terminal ID", y = "Ratio of miniSOG Vesicles to Total Vesicles") +
+  theme(plot.title = element_text(color="Black", size=22,hjust = 0.5),
+        legend.title=element_blank(),
+        axis.title.y=element_text(size=20,margin=margin(0,5,0,0)),
+        axis.title.x=element_text(size=20,margin=margin(5,0,0,0)))
+
+dev.off()
+
+pdf('miniSOGratio_persample_small.pdf',width=4,height=4)
+fd <- data.frame(Sample = c("Lateral Habenula", "Nucleus Accumbens", "Ventral Pallidum"), mRat = c(mean(as.numeric(unlist(T_so[T_so$Sample=="Lateral Habenula",12]))),
+                                                                                                   mean(as.numeric(unlist(T_so[T_so$Sample=="Nucleus Accumbens",12]))),
+                                                                                                   mean(as.numeric(unlist(T_so[T_so$Sample=="Ventral Palladum",12])))))
+
+#T_so[,12] <- T_so$V8/(T_so$V8+T_so$V9)
+
+ggplot(fd,aes(x = Sample,y = mRat,fill = Sample))+geom_col() +
+  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
+  labs(title="",x="Area", y = "Ratio") +
+  theme(plot.title = element_text(color="Black", size=22,hjust = 0.5),
+        legend.title=element_blank(),
+        axis.title.y=element_text(size=20,margin=margin(0,5,0,0)),
+        axis.title.x=element_text(size=20,margin=margin(5,0,0,0)))
+
+dev.off()
+
+
+
+
+#Volume Plot
+
+vol_dat <- data.frame(sizes = c(2*lhab_vd$`Size(nm) - represented as spherical radius`,
+                                2*nacc_vd$`Size(nm) - represented as spherical radius`,
+                                2*vpal_vd$`Size(nm) - represented as spherical radius`),
+                      sample = c(rep("Lateral Habenula", nrow(lhab_vd)),
+                                 rep("Nucleus Accumbens", nrow(nacc_vd)),
+                                 rep("Ventral Pallidum", nrow(vpal_vd))),
+                      type = c(lhab_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                               nacc_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                               vpal_vd$`Type - Whether vesicle is miniSOG labeled or canonical`),
+                      azdis = c(lhab_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`,
+                                nacc_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`,
+                                vpal_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`),
+                      iterm = c(lhab_vd$`Terminal ID - which terminal the vesicle is in`,
+                                nacc_vd$`Terminal ID - which terminal the vesicle is in`,
+                                vpal_vd$`Terminal ID - which terminal the vesicle is in`))
+hda <- vol_dat[vol_dat$sample == 'Lateral Habenula',]
+naa <- vol_dat[vol_dat$sample == 'Nucleus Accumbens',]
+vpa <- vol_dat[vol_dat$sample == 'Ventral Pallidum',]
+T_Sum <- read_excel("D:/Matthew/Neuron_Rush_Sep/Vesicle_Data_Final.xls", 
+                    sheet = "Mito_Data")
+T_Sum$X__1 <- paste(T_Sum$Sample, T_Sum$`Terminal ID`,sep = " ")
+# Sum Volumes
+hda$typeterm <- paste(hda$iterm, hda$type, hda$sample)
+lind <- unique(hda$iterm)
+for(i in 1:length(lind)){
+  datap <- hda[hda$iterm == lind[i],]
+  datapm <-  hda[hda$iterm == lind[i] & hda$type=='miniSOG',]
+  if(i == 1){
+    az = data.frame(VesVol = sum((4/3)*pi*((datap$sizes)/2)^3),
+                    mSOGvol = sum((4/3)*pi*((datapm$sizes)/2)^3),
+                    Term = unique(datap$iterm))
+  }else{
+    az = rbind(az,data.frame(VesVol = sum((4/3)*pi*((datap$sizes)/2)^3),
+                    mSOGvol = sum((4/3)*pi*((datapm$sizes)/2)^3),
+                    Term = unique(datap$iterm)))
+  }
+}
+
+#ak$Term <- as.numeric(sapply(strsplit(as.character(ak$Var1), " "), "[[", 1))
+for(i in 1:nrow(T_Sum[T_Sum$Sample == 'Lateral Habenula',])){
+  if(T_Sum$`Terminal ID`[i]==12){next}
+  cn = az[az$Term == T_Sum$`Terminal ID`[i],]
+  T_Sum[i,8] = cn[1]
+  T_Sum[i,9] = cn[2]
+  T_Sum[i,10] = i
+}
+#Nucleus Accumbens
+naa$typeterm <- paste(naa$iterm, naa$type, naa$sample)
+lind <- unique(naa$iterm)
+for(i in 1:length(lind)){
+  datap <- naa[naa$iterm == lind[i],]
+  datapm <-  naa[naa$iterm == lind[i] & naa$type=='miniSOG',]
+  if(i == 1){
+    az = data.frame(VesVol = sum((4/3)*pi*((datap$sizes)/2)^3),
+                    mSOGvol = sum((4/3)*pi*((datapm$sizes)/2)^3),
+                    Term = unique(datap$iterm))
+  }else{
+    az = rbind(az,data.frame(VesVol = sum((4/3)*pi*((datap$sizes)/2)^3),
+                             mSOGvol = sum((4/3)*pi*((datapm$sizes)/2)^3),
+                             Term = unique(datap$iterm)))
+  }
+}
+
+#ak$Term <- as.numeric(sapply(strsplit(as.character(ak$Var1), " "), "[[", 1))
+for(i in 28 + 1:nrow(T_Sum[T_Sum$Sample == 'Nucleus Accumbens',])){
+  if(T_Sum$`Terminal ID`[i]==12){next}
+  cn = az[az$Term == T_Sum$`Terminal ID`[i],]
+  T_Sum[i,8] = cn[1]
+  T_Sum[i,9] = cn[2]
+  T_Sum[i,10] = i
+}
+
+#Ventral Pallidum
+vpa$typeterm <- paste(vpa$iterm, vpa$type, vpa$sample)
+lind <- unique(vpa$iterm)
+for(i in 1:length(lind)){
+  datap <- vpa[vpa$iterm == lind[i],]
+  datapm <-  vpa[vpa$iterm == lind[i] & vpa$type=='miniSOG',]
+  if(i == 1){
+    az = data.frame(VesVol = sum((4/3)*pi*((datap$sizes)/2)^3),
+                    mSOGvol = sum((4/3)*pi*((datapm$sizes)/2)^3),
+                    Term = unique(datap$iterm))
+  }else{
+    az = rbind(az,data.frame(VesVol = sum((4/3)*pi*((datap$sizes)/2)^3),
+                             mSOGvol = sum((4/3)*pi*((datapm$sizes)/2)^3),
+                             Term = unique(datap$iterm)))
+  }
+}
+
+#ak$Term <- as.numeric(sapply(strsplit(as.character(ak$Var1), " "), "[[", 1))
+for(i in 45 + 1:nrow(T_Sum[T_Sum$Sample == 'Ventral Palladum',])){
+  if(T_Sum$`Terminal ID`[i]==12){next}
+  cn = az[az$Term == T_Sum$`Terminal ID`[i],]
+  T_Sum[i,8] = cn[1]
+  T_Sum[i,9] = cn[2]
+  T_Sum[i,10] = i
+}
+T_Sum <- na.omit(T_Sum)
+T_Sum[,11]<- paste(T_Sum$Sample,T_Sum$ResetIndex)
+
+#format data as x y type sample termid
+ngat <- data.frame(ID = T_Sum$V11,
+                   Tvol = T_Sum$`Terminal Volume (nm^3)`,
+                   Sample = T_Sum$Sample,
+                   iden = rep("Terminal Cytosolic Volume", nrow(T_Sum)))
+nadd <- data.frame(ID = T_Sum$V11,
+                   Tvol = T_Sum$`Total Mito Volume (nm^3)`,
+                   Sample = T_Sum$Sample,
+                   iden = rep("Mitochondrial Volume", nrow(T_Sum)))
+ngat = rbind(ngat,nadd)
+nadd <- data.frame(ID = T_Sum$V11,
+                   Tvol = T_Sum$VesVol,
+                   Sample = T_Sum$Sample,
+                   iden = rep("Total Unlabeled Vesicle Volume", nrow(T_Sum)))
+ngat = rbind(ngat,nadd)
+nadd <- data.frame(ID = T_Sum$V11,
+                   Tvol = T_Sum$mSOGvol,
+                   Sample = T_Sum$Sample,
+                   iden = rep("TotalminiSOG Vesicle Volume", nrow(T_Sum)))
+ngat = rbind(ngat,nadd)
+ngat2 <- ngat
+#get terminal cytosol
+for(i in 1:nrow(ngat[ngat$iden == "Terminal Cytosolic Volume",])){
+  tby <- ngat[i,1]
+  fby <- ngat[ngat[,1] == tby,]
+  cytvol <- fby[1,2]-fby[2,2]-fby[3,2]
+  ngat[i,2]=cytvol
+}
+
+#ngat[,2] <- ngat[,2]*(10^-9)
+
+
+
+pdf('Object_SumVolumes_linear.pdf',width=11,height=9.5)
+ggplot(ngat, aes(x=ID, y=Tvol, fill = iden)) + geom_col() +
+  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
+  scale_x_discrete(limits=T_so$V11) + 
+  scale_y_continuous() + #breaks=c(0,50,100,150,200,500,600,900,1500,4000)) 
+  labs(title="Total Volumes",x="Terminal ID", y = "Volume(um^3)") +
+  theme(plot.title = element_text(color="Black", size=22,hjust = 0.5),
+        legend.title=element_blank(),
+        axis.title.y=element_text(size=20,margin=margin(0,5,0,0)),
+        axis.title.x=element_text(size=20,margin=margin(5,0,0,0)))# +
+ # labs(shape="Type of Vesicles", colour="Area")
+
+dev.off()
+
+pdf('Object_SumVolumes_log.pdf',width=11,height=9.5)
+ggplot(ngat, aes(x=ID, y=Tvol, fill = iden)) + geom_col() +
+  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
+  scale_x_discrete(limits=T_so$V11) + 
+  scale_y_log10() + #breaks=c(0,50,100,150,200,500,600,900,1500,4000)) 
+  labs(title="Total Volumes",x="Terminal ID", y = "Volume(um^3)") +
+  theme(plot.title = element_text(color="Black", size=22,hjust = 0.5),
+        legend.title=element_blank(),
+        axis.title.y=element_text(size=20,margin=margin(0,5,0,0)),
+        axis.title.x=element_text(size=20,margin=margin(5,0,0,0)))# +
+# labs(shape="Type of Vesicles", colour="Area")
+
+dev.off()
+
+
+
+
+
+#Binned Object Volumes
+bindat <- ngat
+sumdat <- bindat
+
+tindex <- unique(sumdat[,1])
+sdat <- data.frame(Termianl = tindex)
+
+for(i in 1:length(tindex)){
+  curte <- sdat[i,1]
+  gmes <- bindat[bindat[,1] == curte,]
+  sdat[i,2] <- gmes[1,2]
+  sdat[i,3] <- gmes[2,2]
+  sdat[i,4] <- gmes[3,2]
+  sdat[i,5] <- gmes[4,2]
+  sdat[i,6] <- gmes[1,3]
+}
+
+names(sdat)<- c("ID", "Terminal Cytosolic Volume", "Mitochondrial Volume", "Total Unlabeled Vesicle Volume", "Total miniSOG Vesicle Volume")
+
+sdat[,7] <- rowSums(sdat[,2:5])
+sdat[,8] <- sdat[,7]*(10^-9)
+
+for(i in 1:length(tindex)){
+  if(sdat[i,8]>1){
+    sdat[i,9] = "Large"
+  }else if(.5<sdat[i,8]&sdat[i,8]<=1){
+    sdat[i,9] = "Medium"
+  }else{
+    sdat[i,9] = "Small"
+    }
+}
+
+for(i in 1:length(sdat[,1])){
+  if(sdat[i,3] == 0){
+    sdat[i,10] <- 'problem'
+  }
+}
+sdat[45,10] <- 'problem'
+sdat_copy <- sdat
+
+sdat <- sdat[is.na(sdat[,10]),]
+
+
+
+ibins <- data.frame(Sample = c("Lateral Habenula","Lateral Habenula","Lateral Habenula", "Nucleus Accumbens", "Nucleus Accumbens", "Ventral Palladum", "Ventral Palladum"),
+                    TerminalSize = c("Large","Medium","Small","Medium","Small","Medium","Small"))
+
+for(i in 1:7){
+  yo = ibins[i,1] == sdat[,6] & ibins[i,2] == sdat[,9]
+  datap = sdat[yo,]
+  #Termianl
+  ibins[i,3] = mean(datap[,2])
+  ibins[i,4] = sd(datap[,2],na.rm = TRUE)
+
+  #Mito
+  ibins[i,5] = mean(datap[,3])
+  ibins[i,6] = sd(datap[,3],na.rm = TRUE)
+
+  #Unalbeled Vesicle
+  ibins[i,7] = mean(datap[,4])
+  ibins[i,8] = sd(datap[,4],na.rm = TRUE)
+
+  #miniSOG Vesicle
+  ibins[i,9] = mean(datap[,5])
+  ibins[i,10] = sd(datap[,5],na.rm = TRUE)
+
+}
+  
+newdata <- melt(ibins[,c(1:3,5,7,9)], id = c('Sample','TerminalSize'))
+SDs <- melt(ibins[,c(1:2,4,6,8,10)], id = c('Sample','TerminalSize'))
+newdata$variable <- as.character(newdata$variable)
+SDs$variable <- as.character(SDs$variable)
+newdata$variable[1:7] = "Cytosolic Volume"
+newdata$variable[8:14] = "Mitochondria Volume"
+newdata$variable[15:21] = "Unlabeled Vesicle Volume"
+newdata$variable[22:28]= "miniSOG Vesicle Volume"
+
+SDs$variable[1:7] = "Cytosolic Volume"
+SDs$variable[8:14] = "Mitochondria Volume"
+SDs$variable[15:21] = "Unlabeled Vesicle Volume"
+SDs$variable[22:28]= "miniSOG Vesicle Volume"
+
+log_nd <- newdata
+log_SDs <- SDs
+log_nd$value <- log_nd$value#* (10^-9)
+log_SDs$value <- log_SDs$value #* (10^-9)
+log_nd[,5] <- log_SDs$value
+
+
+
+#plotdata <- newdata
+#plotdata$value <- plotdata$value *10^-9
+#plotsd <- SDs
+#plotsd$value <- plotsd$value*10^-9
+#plotsd[,5] <- plotsd$value
+
+
+log_nd$variable <- as.factor(log_nd$variable)
+print(levels(log_nd$variable))
+log_nd$variable <- factor(log_nd$variable,levels(log_nd$variable)[c(1,3,4,2)])
+log_nd$logvalue <- log_nd$value
+
+#c("Cytosolic Volume","Mitochondria Volume","Unlabeled Vesicle Volume","miniSOG Vesicle Volume")
+
+pdf('Object_Volumes_withError.pdf',width=11,height=14)
+
+p <- ggplot(log_nd,aes(x =factor(TerminalSize),y=value,group = variable,color = variable, fill = variable)) +
+           geom_col(position = "dodge",color="black")+ 
+            facet_grid(.~Sample, space="free_x", scales = "free_x" ) +
+           scale_y_log10(breaks = c(100000, 1000000,5000000,20000000,50000000,100000000,500000000,1000000000),
+                         labels = c(".0001",".001",".005",".02",".05",".1",".5","1"),
+                         limits = c(1,3e9))+ #expand = c(1,3e9)) +
+           geom_errorbar(aes(ymin = value-V5, ymax = value+V5), width = .2, position = position_dodge(.9),colour='black') +
+  labs(title="Total Volume of Objects", y = "Volume(??m³)",
+       x = "Terminal Sizes: Large > 1??m³ | 0.5??m³ < Medium < 1??m³ | Small < 0.5??m³") +
+  theme(plot.title = element_text(color="Black", size=58,hjust = 0.5,margin = margin(0,0,20,0)),
+        legend.title=element_blank(),
+        axis.title.y=element_text(size=40,margin=margin(0,5,0,0)),
+        axis.title.x=element_text(size=18,margin=margin(5,0,0,0)),
+        axis.text.x=element_text(size=18),
+        axis.text.y=element_text(size=18),
+        strip.text = element_text(face="bold", size=17),
+        legend.text=element_text(size=18),
+        legend.position="bottom",
+        legend.direction="vertical",
+        legend.key.size = unit(1.6, 'lines'),
+        axis.line.x = element_line(color="black", size = .01))  + 
+        coord_cartesian(ylim=c(100000, 3e9))
+                        
+    
+p
+dev.off()
+
+#axis.text.y=element_text(size=25),
+#axis.title.y=element_text(size=40,margin=margin(0,15,0,0)),
+#axis.title.x=element_blank(),
+#axis.text.x=element_blank(),
+#legend.title=element_blank(),
+#legend.text=element_text(size=22,margin=margin(0,0,0,3)),
+#plot.title = element_text(color="Black", size=40,hjust = 0.5,margin=margin(0,30,30,0))
+
+
+#Binned miniSOG Ratios
+bindat <- ngat
+sumdat <- bindat
+
+tindex <- unique(sumdat[,1])
+sdat <- data.frame(Termianl = tindex)
+
+for(i in 1:length(tindex)){
+  curte <- sdat[i,1]
+  gmes <- bindat[bindat[,1] == curte,]
+  sdat[i,2] <- gmes[1,2]
+  sdat[i,3] <- gmes[2,2]
+  sdat[i,4] <- gmes[3,2]
+  sdat[i,5] <- gmes[4,2]
+  sdat[i,6] <- gmes[1,3]
+}
+
+names(sdat)<- c("ID", "Terminal Cytosolic Volume", "Mitochondrial Volume", "Total Unlabeled Vesicle Volume", "Total miniSOG Vesicle Volume")
+
+sdat[,7] <- rowSums(sdat[,2:5])
+sdat[,8] <- sdat[,7]*(10^-9)
+
+for(i in 1:length(tindex)){
+  if(sdat[i,8]>1){
+    sdat[i,9] = "Large"
+  }else if(.5<sdat[i,8]&sdat[i,8]<=1){
+    sdat[i,9] = "Medium"
+  }else{
+    sdat[i,9] = "Small"
+  }
+}
+
+for(i in 1:length(sdat[,1])){
+  if(sdat[i,3] == 0){
+    sdat[i,10] <- 'problem'
+  }
+}
+sdat[45,10] <- 'problem'
+sdat_copy <- sdat
+
+sdat <- sdat[is.na(sdat[,10]),]
+
+refind<- data.frame(Oldind = T_Sum$`Terminal ID`,newind =  T_Sum$ResetIndex, Sample = T_Sum$Sample)
+#get ratios into sdat
+for(i in 1:length(sdat[,1])){
+  
+  ff = as.character(sdat[i,1])
+  ff3 = as.numeric(sapply(strsplit(ff, " "), "[[", 3))
+  ff2 = paste(sapply(strsplit(ff, " "), "[[", 1),sapply(strsplit(ff, " "), "[[", 2))
+  ff4 = refind[refind$newind == ff3 & refind$Sample == ff2,1]
+  if(ff2 == "Ventral Palladum"){
+    ff2 = "Ventral Pallidum"
+  }
+  ff4 = paste(ff2,ff4)
+  
+  
+  
+  cdatp = vol_dat[paste(vol_dat$sample,vol_dat$iterm,sep = " ") == ff4,]
+  sdat[i,11] = nrow(cdatp[cdatp$type=="miniSOG",])
+  sdat[i,12] = nrow(cdatp[cdatp$type=="Canonical",])
+}
+
+sdat[,13] = sdat[,11]/(sdat[,11] + sdat[,12])
+
+
+
+
+ibins <- data.frame(Sample = c("Lateral Habenula","Lateral Habenula","Lateral Habenula", "Nucleus Accumbens", "Nucleus Accumbens", "Ventral Palladum", "Ventral Palladum"),
+                    TerminalSize = c("Large","Medium","Small","Medium","Small","Medium","Small"))
+
+for(i in 1:7){
+  yo = ibins[i,1] == sdat[,6] & ibins[i,2] == sdat[,9]
+  datap = sdat[yo,]
+  #Termianl
+  ibins[i,3] = mean(datap[,2])
+  ibins[i,4] = sd(datap[,2],na.rm = TRUE)
+  
+  #Mito
+  ibins[i,5] = mean(datap[,3])
+  ibins[i,6] = sd(datap[,3],na.rm = TRUE)
+  
+  #Unalbeled Vesicle
+  ibins[i,7] = mean(datap[,4])
+  ibins[i,8] = sd(datap[,4],na.rm = TRUE)
+  
+  #miniSOG Vesicle
+  ibins[i,9] = mean(datap[,5])
+  ibins[i,10] = sd(datap[,5],na.rm = TRUE)
+  
+  #miniSOG Ratio
+  ibins[i,11] = mean(datap[,13])
+  ibins[i,12] = sd(datap[,13],na.rm = TRUE)
+}
+
+newdata <- melt(ibins[,c(1:2,11)], id = c('Sample','TerminalSize'))
+SDs <- melt(ibins[,c(1:2,12)], id = c('Sample','TerminalSize'))
+newdata$variable <- as.character(newdata$variable)
+SDs$variable <- as.character(SDs$variable)
+newdata$variable[1:7] = "miniSOG Ratio"
+#newdata$variable[8:14] = "Mitochondria Volume"
+#newdata$variable[15:21] = "Unlabeled Vesicle Volume"
+#newdata$variable[22:28]= "miniSOG Vesicle Volume"
+
+SDs$variable[1:7] = "miniSOG Ratio"
+#SDs$variable[8:14] = "Mitochondria Volume"
+#SDs$variable[15:21] = "Unlabeled Vesicle Volume"
+#SDs$variable[22:28]= "miniSOG Vesicle Volume"
+
+log_nd <- newdata
+log_SDs <- SDs
+log_nd$value <- log_nd$value#* (10^-9)
+log_SDs$value <- log_SDs$value #* (10^-9)
+log_nd[,5] <- log_SDs$value
+
+
+
+#plotdata <- newdata
+#plotdata$value <- plotdata$value *10^-9
+#plotsd <- SDs
+#plotsd$value <- plotsd$value*10^-9
+#plotsd[,5] <- plotsd$value
+
+
+log_nd$variable <- as.factor(log_nd$variable)
+print(levels(log_nd$variable))
+#log_nd$variable <- factor(log_nd$variable,levels(log_nd$variable)[c(1,3,4,2)])
+log_nd$logvalue <- log_nd$value
+
+#c("Cytosolic Volume","Mitochondria Volume","Unlabeled Vesicle Volume","miniSOG Vesicle Volume")
+
+pdf('miniSOG_Ratios_withError_small.pdf',width=7,height=7)
+
+p <- ggplot(log_nd,aes(x =factor(TerminalSize),y=value,group = variable,color = variable, fill = TerminalSize)) +
+  geom_col(position = "dodge",color="black")+ 
+  facet_grid(.~Sample, space="free_x", scales = "free_x" ) +
+  geom_errorbar(aes(ymin = value-V5, ymax = value+V5), width = .2, position = position_dodge(.9),colour='black') +
+  labs(title="", y = "Ratio",
+       x = "Terminal Sizes: Large > 1??m³ | 0.5??m³ < Medium < 1??m³ | Small < 0.5??m³") +
+  theme(plot.title = element_text(color="Black", size=30,hjust = 0.5,margin = margin(0,135,20,0), face = 'bold'),
+        legend.title=element_blank(),
+        axis.title.y=element_text(size=32,margin=margin(0,5,0,0)),
+        axis.title.x=element_text(size=18,margin=margin(5,0,0,0)),
+        axis.text.x=element_text(size=18),
+        axis.text.y=element_text(size=24),
+        strip.text = element_text(face="bold", size=17),
+        legend.text=element_text(size=24),
+        #legend.position="bottom",
+        legend.direction="vertical",
+        legend.key.size = unit(1.8, 'lines'),
+        axis.line.x = element_line(color="black", size = .01),
+        legend.position = c(.11, .935),
+        legend.background = element_rect(colour = 'black', fill = 'white', linetype='solid'))  + 
+  scale_fill_manual(values=c("#a987bc", "#ce9e50", "#649e4a"))
+
+p
+dev.off()
+
+## Vesicle Counts New
+coun_t <- data.frame(sizes = c(lhab_vd$`Size(nm) - represented as spherical radius`,
+                               nacc_vd$`Size(nm) - represented as spherical radius`,
+                               vpal_vd$`Size(nm) - represented as spherical radius`),
+                     sample = c(rep("Lateral Habenula", nrow(lhab_vd)),
+                                rep("Nucleus Accumbens", nrow(nacc_vd)),
+                                rep("Ventral Pallidum", nrow(vpal_vd))),
+                     type = c(lhab_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                              nacc_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                              vpal_vd$`Type - Whether vesicle is miniSOG labeled or canonical`),
+                     term = c(lhab_vd$`Terminal ID - which terminal the vesicle is in`,
+                              nacc_vd$`Terminal ID - which terminal the vesicle is in`,
+                              vpal_vd$`Terminal ID - which terminal the vesicle is in`)
+                     )
+coun_t[,5] <- paste(coun_t[,2],coun_t[,4])
+zsort =data.frame(Term =  unique(coun_t[,5]))
+for(i in 1:length(zsort[,1])){
+  ff = as.character(zsort[i,1])
+  ff3 = as.numeric(sapply(strsplit(ff, " "), "[[", 3))
+  ff2 = paste(sapply(strsplit(ff, " "), "[[", 1),sapply(strsplit(ff, " "), "[[", 2))
+  #ff4 = refind[refind$newind == ff3 & refind$Sample == ff2,1]
+  datp <- coun_t[as.character(coun_t$sample) == ff2 & as.numeric(coun_t$term) == as.numeric(ff3),]
+  zsort[i,2] = nrow(datp[datp$type == 'miniSOG',])
+  zsort[i,3] = nrow(datp[datp$type == 'Canonical',])
+  zsort[i,4] = ff3
+  zsort[i,5] = ff2
+}
+
+zsort2 <- melt(zsort, id = c("V4","V5","Term"))
+
+positions = paste(zsort2$V5,zsort$V4)
+#positions = c('Lateral Habenula 1','Lateral Habenula 2','Lateral Habenula 3','Lateral Habenula 4','Lateral Habenula 1','Lateral Habenula 1','Lateral Habenula 1','Lateral Habenula 1',
+#              'Lateral Habenula 1','Lateral Habenula 1','Lateral Habenula 1','Lateral Habenula 1',)
+pdf('Ves_Counts.pdf',width=5,height=11.5/2)
+pg <- ggplot(zsort2,aes(Term,value,color=V5,shape = variable)) + geom_point() + geom_line(aes(group=Term,color = V5)) +
+  scale_y_log10(breaks = c(10,20,25,50,75,100,150,200,250,300,400,500,750,1000,1250,2000,3000)) +
+  guides(colour = guide_legend(override.aes = list(size=10))) +
+  labs(title='Vesicle Counts by Terminal', y = "Number of Vesicles",
+       x = "Terminal") +
+  theme(legend.position="none",
+        plot.title = element_text(color="Black", size=20,hjust = 0.5,margin = margin(0,0,10,0), face = 'bold'),
+        legend.title=element_blank(),
+        axis.title.y=element_text(size=20,margin=margin(0,5,0,0)),
+        axis.title.x=element_text(size=18,margin=margin(5,0,0,0)),
+        axis.text.x=element_text(size=4,angle = 45, hjust = 1, face = "bold"),
+        axis.text.y=element_text(size=8),
+        legend.text=element_text(size=8) 
+        ) + scale_x_discrete(limits = positions[1:50])
+
+pg
+dev.off()
+
+nrowsort = rbind(log_nd[4:7,],log_nd[1:3,])
+nrowsort[,1] = factor(nrowsort[,1],levels(nrowsort[,1])[c(2,3,1)])
+
+pdf('miniSOG_Ratios_withError_smalln_R.pdf',width=6,height=6.3)
+p <- ggplot(nrowsort,aes(x =factor(TerminalSize),y=value,group = variable,color = variable, fill = TerminalSize)) +
+  geom_col(position = "dodge",color="black")+ 
+  facet_grid(.~Sample, space="free_x", scales = "free_x" ) +
+  geom_errorbar(aes(ymin = value-V5, ymax = value+V5), width = .2, position = position_dodge(.9),colour='black') +
+  labs(title="", y = "Ratio",
+       x = "") +
+  theme(plot.title = element_text(color="Black", size=30,hjust = 0.5,margin = margin(0,135,20,0), face = 'bold'),
+        legend.title=element_blank(),
+        axis.title.y=element_text(size=32,margin=margin(0,5,0,0)),
+        axis.title.x=element_text(size=16,margin=margin(5,0,0,0)),
+        axis.text.x=element_text(size=14),
+        axis.text.y=element_text(size=24),
+        strip.text = element_text(face="bold", size=11),
+        legend.text=element_text(size=24),
+        #legend.position="bottom",
+        legend.direction="vertical",
+        legend.key.size = unit(1.8, 'lines'),
+        axis.line.x = element_line(color="black", size = .01),
+        legend.position = c(3, 3),
+        legend.background = element_rect(colour = 'black', fill = 'white', linetype='solid'),
+        panel.grid.major.y = element_line(colour='grey',size=.3), panel.grid.minor = element_blank(),
+        panel.grid.major.x = element_blank(),
+        rect = element_rect(fill = "transparent"),
+        panel.background = element_blank(),
+        panel.border=element_rect(colour="grey",size=.5))  + 
+  scale_fill_manual(values=c("#a987bc", "#ce9e50", "#649e4a"))+  scale_y_continuous(expand = c(0,0),
+                                                                                    limits = c(0,.5))#+ scale_y_discrete(expand = c(0, NA))
+
+p
+dev.off()
+
+
+
+#Binned Object Volumes
+bindat <- ngat
+sumdat <- bindat
+
+tindex <- unique(sumdat[,1])
+sdat <- data.frame(Termianl = tindex)
+
+for(i in 1:length(tindex)){
+  curte <- sdat[i,1]
+  gmes <- bindat[bindat[,1] == curte,]
+  sdat[i,2] <- gmes[1,2]
+  sdat[i,3] <- gmes[2,2]
+  sdat[i,4] <- gmes[3,2]
+  sdat[i,5] <- gmes[4,2]
+  sdat[i,6] <- gmes[1,3]
+}
+
+names(sdat)<- c("ID", "Terminal Cytosolic Volume", "Mitochondrial Volume", "Total Unlabeled Vesicle Volume", "Total miniSOG Vesicle Volume")
+
+sdat[,7] <- rowSums(sdat[,2:5])
+sdat[,8] <- sdat[,7]*(10^-9)
+
+for(i in 1:length(tindex)){
+  if(sdat[i,8]>1){
+    sdat[i,9] = "Large"
+  }else if(.5<sdat[i,8]&sdat[i,8]<=1){
+    sdat[i,9] = "Medium"
+  }else{
+    sdat[i,9] = "Small"
+  }
+}
+
+for(i in 1:length(sdat[,1])){
+  if(sdat[i,3] == 0){
+    sdat[i,10] <- 'problem'
+  }
+}
+sdat[45,10] <- 'problem'
+sdat_copy <- sdat
+
+sdat <- sdat[is.na(sdat[,10]),]
+
+
+
+ibins <- data.frame(Sample = c("Lateral Habenula","Lateral Habenula","Lateral Habenula", "Nucleus Accumbens", "Nucleus Accumbens", "Ventral Palladum", "Ventral Palladum"),
+                    TerminalSize = c("Large","Medium","Small","Medium","Small","Medium","Small"))
+
+for(i in 1:7){
+  yo = ibins[i,1] == sdat[,6] & ibins[i,2] == sdat[,9]
+  datap = sdat[yo,]
+  #Termianl
+  ibins[i,3] = mean(datap[,2])
+  ibins[i,4] = sd(datap[,2],na.rm = TRUE)
+  
+  #Mito
+  ibins[i,5] = mean(datap[,3])
+  ibins[i,6] = sd(datap[,3],na.rm = TRUE)
+  
+  #Unalbeled Vesicle
+  ibins[i,7] = mean(datap[,4])
+  ibins[i,8] = sd(datap[,4],na.rm = TRUE)
+  
+  #miniSOG Vesicle
+  ibins[i,9] = mean(datap[,5])
+  ibins[i,10] = sd(datap[,5],na.rm = TRUE)
+  
+}
+
+newdata <- melt(ibins[,c(1:3,5,7,9)], id = c('Sample','TerminalSize'))
+SDs <- melt(ibins[,c(1:2,4,6,8,10)], id = c('Sample','TerminalSize'))
+newdata$variable <- as.character(newdata$variable)
+SDs$variable <- as.character(SDs$variable)
+newdata$variable[1:7] = "Cytosolic Volume"
+newdata$variable[8:14] = "Mitochondria Volume"
+newdata$variable[15:21] = "Unlabeled Vesicle Volume"
+newdata$variable[22:28]= "miniSOG Vesicle Volume"
+
+SDs$variable[1:7] = "Cytosolic Volume"
+SDs$variable[8:14] = "Mitochondria Volume"
+SDs$variable[15:21] = "Unlabeled Vesicle Volume"
+SDs$variable[22:28]= "miniSOG Vesicle Volume"
+
+log_nd <- newdata
+log_SDs <- SDs
+log_nd$value <- log_nd$value#* (10^-9)
+log_SDs$value <- log_SDs$value #* (10^-9)
+log_nd[,5] <- log_SDs$value
+
+
+
+#plotdata <- newdata
+#plotdata$value <- plotdata$value *10^-9
+#plotsd <- SDs
+#plotsd$value <- plotsd$value*10^-9
+#plotsd[,5] <- plotsd$value
+
+
+log_nd$variable <- as.factor(log_nd$variable)
+print(levels(log_nd$variable))
+log_nd$variable <- factor(log_nd$variable,levels(log_nd$variable)[c(1,3,4,2)])
+log_nd$logvalue <- log_nd$value
+
+#c("Cytosolic Volume","Mitochondria Volume","Unlabeled Vesicle Volume","miniSOG Vesicle Volume")
+
+
+
+
+rsortvol = log_nd
+log_nd[,1] = factor(log_nd[,1],levels(log_nd[,1])[c(2,3,1)])
+
+
+
+pdf('Object_Volumes_withError_npaperplotNNN.pdf',width=7,height=8.2)
+p <- ggplot(log_nd,aes(x =factor(TerminalSize),y=value,group = variable,color = variable, fill = variable)) +
+  geom_col(position = "dodge",color="black")+ 
+  facet_grid(.~Sample, space="free_x", scales = "free_x" ) +
+  scale_y_log10(breaks = c(100000, 1000000,5000000,20000000,50000000,100000000,500000000,1000000000),
+                labels = c(".0001",".001",".005",".02",".05",".1",".5","1"),
+                limits = c(1,3e9))+ #expand = c(1,3e9)) +
+  geom_errorbar(aes(ymin = value-V5, ymax = value+V5), width = .2, position = position_dodge(.9),colour='black') +
+  labs(title="", y = "Volume",
+       x = "") +
+  theme(plot.title = element_text(color="Black", size=58,hjust = 0.5,margin = margin(0,0,20,0)),
+        legend.title=element_blank(),
+        axis.title.y=element_text(size=40,margin=margin(0,5,0,0)),
+        axis.title.x=element_text(size=16,margin=margin(5,0,0,0)),
+        axis.text.x=element_text(size=14),
+        axis.text.y=element_text(size=18),
+        strip.text = element_text(face="bold", size=11),
+        legend.text=element_text(size=13),
+        legend.position="bottom",
+        legend.direction="vertical",
+        legend.key.size = unit(1.6, 'lines'),
+        legend.background = element_rect(colour = 'black', fill = 'transparent', linetype='solid'),
+        axis.line.x = element_line(color="black", size = .01),
+        panel.grid.major.y = element_line(colour='grey',size=.3), panel.grid.minor = element_blank(),
+        panel.grid.major.x = element_blank(),
+        rect = element_rect(fill = "transparent"),
+        panel.background = element_blank(),
+        panel.border=element_rect(colour="grey",size=.5))  + 
+  coord_cartesian(ylim=c(100000, 3e9))
+
+
+p
+dev.off()
+
+library(readxl)
+library(ggplot2)
+library(wesanderson)
+setwd('D:/Matthew/')
+pal <- wes_palette(21, name = "Zissou1", type = "continuous")
+
+lhab_vd <- read_excel("Neuron_Rush_Sep/Vesicle_Data_Final.xls", 
+                      sheet = "Lateral_Habenula_Vesicle_Data")
+lhab_vd = lhab_vd[lhab_vd$`Size(nm) - represented as spherical radius` != 0,]
+nacc_vd <- read_excel("Neuron_Rush_Sep/Vesicle_Data_Final.xls", 
+                      sheet = "Nucleas_Accumbens_Vesicle_Data")
+nacc_vd = nacc_vd[nacc_vd$`Size(nm) - represented as spherical radius` != 0,]
+vpal_vd <- read_excel("Neuron_Rush_Sep/Vesicle_Data_Final.xls", 
+                      sheet = "Ventral_Palladum_Vesicle_Data")
+vpal_vd = vpal_vd[vpal_vd$`Size(nm) - represented as spherical radius` != 0,]
+setwd('D:/Matthew/Neuron_Rush_Sep/Plots')
+
+## Vesicle Sizes by Sample
+size_d <- data.frame(sizes = c(lhab_vd$`Size(nm) - represented as spherical radius`,
+                                     nacc_vd$`Size(nm) - represented as spherical radius`,
+                                     vpal_vd$`Size(nm) - represented as spherical radius`),
+                     sample = c(rep("Lateral Habenula", nrow(lhab_vd)),
+                                rep("Nucleas Accumbens", nrow(nacc_vd)),
+                                rep("Ventral Palladum", nrow(vpal_vd))))
+size_d$sizes <- size_d$sizes*2
+size_d$sample <- as.factor(size_d$sample)
+ylimmin = 15
+ylimmax = 103
+
+jpeg('samplessizeplot.jpg')
+#p <- ggplot(size_d, aes(x=sample, y=sizes)) + 
+ # geom_violin() 
+#p
+
+
+# Change color by groups
+dp <- ggplot(size_d, aes(x=sample, y=sizes, fill=sample)) + 
+  geom_violin(trim=FALSE)+
+  geom_boxplot(width=0.1, fill="white")+
+  labs(title="Vesicle Sizes by Sample",x="Sample", y = "Vesicle Diameter (nm)")
+dp + scale_fill_brewer(palette="Dark2") + theme(
+  panel.background = element_rect(fill = "white",
+                                  colour = "white",
+                                  size = 0.5, linetype = "solid"),
+  panel.grid.major = element_line(size = 0.5, linetype = 'solid',
+                                  colour = "grey"), 
+  panel.grid.minor = element_line(size = 0.25, linetype = 'solid',
+                                  colour = "white"),
+  axis.text.y=element_text(size=10),
+  axis.title.y=element_text(size=20),
+  axis.title.x=element_blank(),
+  axis.text.x=element_blank(),
+  plot.title = element_text(color="Black", size=30,hjust = 0.5)
+) + ylim(ylimmin,ylimmax)
+#center title
+layer_scales(dp)$y$range$range
+dev.off()
+
+
+
+## Vesicle Sizes by Vesicle Type & Sample
+pdf('typesizeplot2.pdf',width=11,height=8)
+size_t <- data.frame(sizes = c(lhab_vd$`Size(nm) - represented as spherical radius`,
+                               nacc_vd$`Size(nm) - represented as spherical radius`,
+                               vpal_vd$`Size(nm) - represented as spherical radius`),
+                     sample = c(rep("Lateral Habenula", nrow(lhab_vd)),
+                                rep("Nucleus Accumbens", nrow(nacc_vd)),
+                                rep("Ventral Pallidum", nrow(vpal_vd))),
+                     type = c(lhab_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                              nacc_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                              vpal_vd$`Type - Whether vesicle is miniSOG labeled or canonical`))
+
+size_t$type <- as.character(size_t$type)
+size_t[size_t$type == 'Canonical',3] = rep('Unlabeled',length(size_t[size_t$type == 'Canonical',1]))
+size_t$type <- as.factor(size_t$type)
+size_t$sizes <- size_t$sizes*2
+size_t$sampletype <- as.factor(paste(size_t$sample, size_t$type,sep = ' '))
+size_t <- size_t[order(size_t$type),]
+size_t$sampletype <- factor(size_t$sampletype, levels = c("Lateral Habenula miniSOG", "Nucleus Accumbens miniSOG", "Ventral Pallidum miniSOG",
+                                                          "Lateral Habenula Unlabeled", "Nucleus Accumbens Unlabeled","Ventral Pallidum Unlabeled"))
+#size_t = na.omit(size_t)
+palte <- wes_palette(4, name = "GrandBudapest1")
+pt2 <- wes_palette(4, name = "GrandBudapest1")
+pt3 <- wes_palette(4, name = "GrandBudapest2")
+pt4 <- wes_palette(4, name = "Cavalcanti1")
+palte <- c(pt2[2],pt3[3],pt2[4],pt3[4],pt4[4],pt3[2])
+
+tp <- ggplot(size_t, aes(x=sampletype, y=sizes, fill=sampletype)) + 
+  geom_violin(trim=FALSE,scale = "width", width = .7,lwd=.38,bw = 2.5)+ 
+  scale_fill_manual(values = palte) +
+  geom_boxplot(width=0.1, fill="white",outlier.shape = NA)+
+  labs(title="Vesicle Sizes by Sample and Type",x="Sample", y = "Vesicle Diameter (nm)")
+
+tp + #scale_fill_brewer(palette="Dark2") + 
+  theme(panel.background = element_rect(fill = "white",
+                                  colour = "white",
+                                  size = 0.5, linetype = "solid"),
+  panel.grid.major = element_line(size = 0.5, linetype = 'solid',
+                                  colour = "grey"), 
+  panel.grid.minor = element_line(size = 0.25, linetype = 'solid',
+                                  colour = "white"),
+  axis.text.y=element_text(size=10),
+  axis.title.y=element_text(size=20,margin=margin(0,15,0,0)),
+  axis.title.x=element_blank(),
+  axis.text.x=element_blank(),
+  legend.title=element_blank(),
+  legend.text=element_text(size=11,margin=margin(0,0,0,3)),
+  plot.title = element_text(color="Black", size=22,hjust = 0.5)
+) + scale_y_continuous(breaks = c(30,40,50,60,70,80,90), limits = c(25,85))
+
+dev.off()
+
+
+## Distance to AZ, miniSog vs unLabeled
+#box
+azdat <- data.frame(sizes = c(lhab_vd$`Size(nm) - represented as spherical radius`,
+                               nacc_vd$`Size(nm) - represented as spherical radius`,
+                               vpal_vd$`Size(nm) - represented as spherical radius`),
+                    sample = c(rep("Lateral Habenula", nrow(lhab_vd)),
+                               rep("Nucleas Accumbens", nrow(nacc_vd)),
+                               rep("Ventral Palladum", nrow(vpal_vd))),
+                    type = c(lhab_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                             nacc_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                             vpal_vd$`Type - Whether vesicle is miniSOG labeled or canonical`),
+                    azdist = c(lhab_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`,
+                               nacc_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`,
+                               vpal_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`))
+azdat$type <- as.character(azdat$type)
+azdat[azdat$type == 'Canonical',3] = rep('Unlabeled',length(azdat[azdat$type == 'Canonical',1]))
+azdat$type <- as.factor(azdat$type)
+jpeg('typeAZplot.jpg')
+azdat$type <- as.factor(azdat$type)
+ap <- ggplot(azdat, aes(y=azdist, x=type, fill = type)) + geom_boxplot(alpha=.9)
+ap + scale_colour_manual(values = palte) + ylim(NA,1300) +
+  labs(title="Distance to Active Zone", y = "Distance (nm)") +
+  theme(axis.text.y=element_text(size=10),
+        axis.title.y=element_text(size=20),
+        axis.title.x=element_blank(),
+        axis.text.x=element_blank(),
+        plot.title = element_text(color="Black", size=30,hjust = 0.5))
+
+dev.off()
+#density 
+jpeg('typeAZplotd.jpg')
+palte <- wes_palette(4, name = "Darjeeling1")
+ap <- ggplot(azdat, aes(x=azdist, colour = type))  + geom_density()
+ap + scale_colour_manual(values = palte) +
+  labs(title="Active Zone Distance by Vesicle Type", y = "Density", x = "Distance to Active Zone (nm)") +
+  theme(axis.text.y=element_text(size=10),
+        axis.title.y=element_text(size=20),
+        axis.title.x=element_text(size=20),
+        axis.text.x=element_text(size=10),
+        plot.title = element_text(color="Black", size=24,hjust = 0.5))
+
+dev.off()
+
+
+
+## Size vs AZ vs Sample 
+azdat <- data.frame(sizes = c(lhab_vd$`Size(nm) - represented as spherical radius`,
+                              nacc_vd$`Size(nm) - represented as spherical radius`,
+                              vpal_vd$`Size(nm) - represented as spherical radius`),
+                    sample = c(rep("Lateral Habenula", nrow(lhab_vd)),
+                               rep("Nucleas Accumbens", nrow(nacc_vd)),
+                               rep("Ventral Palladum", nrow(vpal_vd))),
+                    type = c(lhab_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                             nacc_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                             vpal_vd$`Type - Whether vesicle is miniSOG labeled or canonical`),
+                    azdist = c(lhab_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`,
+                               nacc_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`,
+                               vpal_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`))
+azdat$type <- as.character(azdat$type)
+azdat[azdat$type == 'Canonical',3] = rep('Unlabeled',length(azdat[azdat$type == 'Canonical',1]))
+azdat$type <- as.factor(azdat$type)
+jpeg('Size_AZ_Sample.jpg')
+azdat$sizes <- azdat$sizes*2
+sas <- ggplot(azdat, aes(y = azdist, x = sizes, color = sample)) + geom_point(alpha = .5,shape=20, size = 1)#,alpha = 0.15)
+sas +  scale_fill_brewer(palette="Dark2") + ylim(NA,4000) + xlim(NA,90)+ guides(colour = guide_legend(override.aes = list(size=8))) +
+  labs(title="Vesicle Size and Distance to Active Zone", y = "Distance to Actize Zone(nm)", x = "Vesicle Diameter (nm)",subtitle = "Each point represents a single vesicle")+
+  theme(axis.text.y=element_text(size=8),
+        axis.title.y=element_text(size=10),
+        axis.title.x=element_text(size=10),
+        axis.text.x=element_text(size=8),
+        plot.title = element_text(color="Black", size=18,hjust = 0.5))
+dev.off()
+
+# Terminal Ratio of miniSOG ## Data Prep
+rdat <- data.frame(sizes = c(lhab_vd$`Size(nm) - represented as spherical radius`,
+                              nacc_vd$`Size(nm) - represented as spherical radius`,
+                              vpal_vd$`Size(nm) - represented as spherical radius`),
+                    sample = c(rep("Lateral Habenula", nrow(lhab_vd)),
+                               rep("Nucleas Accumbens", nrow(nacc_vd)),
+                               rep("Ventral Palladum", nrow(vpal_vd))),
+                    type = c(lhab_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                             nacc_vd$`Type - Whether vesicle is miniSOG labeled or canonical`,
+                             vpal_vd$`Type - Whether vesicle is miniSOG labeled or canonical`),
+                    azdist = c(lhab_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`,
+                               nacc_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`,
+                               vpal_vd$`Distance to Active Zone (nm) - distance from vesicle centroid to nearest vertex of Active Zone`),
+                    term = c(lhab_vd$`Terminal ID - which terminal the vesicle is in`,
+                             nacc_vd$`Terminal ID - which terminal the vesicle is in`,
+                             vpal_vd$`Terminal ID - which terminal the vesicle is in`))
+
+#reset terminal index
+l <- lhab_vd
+n <- nacc_vd
+v <- vpal_vd
+#lateral habenula
+i_l <- unique(l$`Terminal ID - which terminal the vesicle is in`)
+i_lr <- 1:length(i_l)
+for (i in 1:length(i_l)) {
+  ur = l[l$`Terminal ID - which terminal the vesicle is in` == i_l[i],]
+  ur$`Terminal ID - which terminal the vesicle is in` = as.double(rep(i_lr[i],length(ur$`Terminal ID - which terminal the vesicle is in`)))
+  l[l$`Terminal ID - which terminal the vesicle is in` == i_l[i],] = ur
+}
+#nucleas accumbens
+i_n <- unique(n$`Terminal ID - which terminal the vesicle is in`)
+i_nr <- 1:length(i_n)
+for (i in 1:length(i_n)) {
+  ur = n[n$`Terminal ID - which terminal the vesicle is in` == i_n[i],]
+  ur$`Terminal ID - which terminal the vesicle is in` = as.double(rep(i_nr[i],length(ur$`Terminal ID - which terminal the vesicle is in`)))
+  n[n$`Terminal ID - which terminal the vesicle is in` == i_n[i],] = ur
+}
+#ventral palladum
+i_v <- unique(v$`Terminal ID - which terminal the vesicle is in`)
+i_vr <- 1:length(i_v)
+for (i in 1:length(i_v)) {
+  ur = v[v$`Terminal ID - which terminal the vesicle is in` == i_v[i],]
+  ur$`Terminal ID - which terminal the vesicle is in` = as.double(rep(i_vr[i],length(ur$`Terminal ID - which terminal the vesicle is in`)))
+  v[v$`Terminal ID - which terminal the vesicle is in` == i_v[i],] = ur
+}
+term_sum <- read_excel("D:/Matthew/Neuron_Rush_Sep/Vesicle_Data_Final.xls", 
+                      sheet = "Mito_Data")
+
+for (i in 1:length(i_lr)){
+  cc <- l[l$`Terminal ID - which terminal the vesicle is in` == i_lr[i],]
+  cc1 <- cc[cc$`Type - Whether vesicle is miniSOG labeled or canonical` == "miniSOG",]
+  cc2 <- cc[cc$`Type - Whether vesicle is miniSOG labeled or canonical` == "Canonical",]
+  term_sum[term_sum$ResetIndex == i_lr[i] & term_sum$Sample == 'Lateral Habenula',8] <- nrow(cc1[,1])
+  term_sum[term_sum$ResetIndex == i_lr[i] & term_sum$Sample == 'Lateral Habenula',9] <- nrow(cc2[,1])
+}
+for (i in 1:length(i_nr)){
+  cc <- n[n$`Terminal ID - which terminal the vesicle is in` == i_nr[i],]
+  cc1 <- cc[cc$`Type - Whether vesicle is miniSOG labeled or canonical` == "miniSOG",]
+  cc2 <- cc[cc$`Type - Whether vesicle is miniSOG labeled or canonical` == "Canonical",]
+  term_sum[term_sum$ResetIndex == i_nr[i] & term_sum$Sample == 'Nucleus Accumbens',8] <- nrow(cc1[,1])
+  term_sum[term_sum$ResetIndex == i_nr[i] & term_sum$Sample == 'Nucleus Accumbens',9] <- nrow(cc2[,1])
+}
+for (i in 1:length(i_vr)){
+  cc <- v[v$`Terminal ID - which terminal the vesicle is in` == i_vr[i],]
+  cc1 <- cc[cc$`Type - Whether vesicle is miniSOG labeled or canonical` == "miniSOG",]
+  cc2 <- cc[cc$`Type - Whether vesicle is miniSOG labeled or canonical` == "Canonical",]
+  term_sum[term_sum$ResetIndex == i_vr[i] & term_sum$Sample == 'Ventral Palladum',8] <- nrow(cc1[,1])
+  term_sum[term_sum$ResetIndex == i_vr[i] & term_sum$Sample == 'Ventral Palladum',9] <- nrow(cc2[,1])
+}
+
+#nacc term 9 is screwed up
+term_sum = term_sum[term_sum[,8] != 0,]
+term_sum[,10] <- paste(term_sum$Sample, term_sum$ResetIndex,sep = ' ')
+term_sum <- term_sum[-28,]
+term_sum <- term_sum[order(term_sum$V9+term_sum$V8),]
+#### Ready to plot
+jpeg('Terminal_Summary.jpg')
+palte <- wes_palette(4, name = "GrandBudapest1")
+p <- ggplot(term_sum, aes(x = 1:length(term_sum$V10)))
+p <- p + geom_line(aes(y = term_sum$V8,colour = "miniSOG Vesicle Count")) + 
+    geom_line(aes(y = term_sum$V9,colour = "Unlabeled Vesicle Count")) +
+    coord_trans(y = "log10") +
+  theme(x)
+    
+p
+
+dev.off()
+
+
+
+
+
+
+
+
+
+
+
+
-- 
GitLab