library(readxl)
library(data.table)
library(ggstatsplot)
library(ggplot2)
library(gridExtra)
library(ggstatsplot)
library(ggsignif)
library(showtext)
library(latex2exp)
showtext_auto()
font_add('sung','simsun.ttc')

read_xlsx('china_us_data.xlsx')->dat
setDT(dat)

g<-c('1'='1同伴设置（中国）' ,
'2'='2同伴设置（美国）' ,
'8'='8基准设置（中国）' ,
'9'='9基准设置（美国）')

dat[,.N,treatment]
dat[,treatment:=g[as.character(as.integer(treatment))]]
dat[,.N,treatment]

dat<-dat[!is.na(treatment)]
dat[,treatment:=gsub('^\\d+','',treatment)]
setnames(dat,'ratio','outcome')



my.points.arg<-list(position = ggplot2::position_jitterdodge(dodge.width = 0.6), 
                    alpha= 0.75, size = 3, stroke = 0)
					
gg<-c(
'g1'='基准设置（中国） 基准设置（美国）',
'g2'='同伴设置（中国） 同伴设置（美国）'
)

setdiff(unlist(strsplit(gg,"\\s+")) ,dat[,unique(treatment)])


col16 = c('#e6194b', '#3cb44b', '#ffe119', '#0082c8',
          '#f58231', '#911eb4', '#46f0f0', '#f032e6',
          '#d2f53c', '#fabebe', '#008080', '#e6beff',
          '#aa6e28', '#fffac8', '#800000', '#aaffc3')

col16<-rep('gray50',16)		  
	  
col16<-setNames(col16[1:dat[,length(unique(treatment))]],dat[,unique(treatment)])
		  

strsplit(gg,"\\s+")->gg
all(unlist(gg) %in% dat[,treatment])

my.points.arg<-list(position = ggplot2::position_jitterdodge(dodge.width = 0.6), 
                    alpha= 0.5, size = 2.8, stroke = 0)
					
					

lapply(1:length(gg),function(ind)
{
inter.data<-dat[treatment %in% gg[[ind]]]
inter.data[,treatment:=ordered(treatment,levels=gg[[ind]])]

t(combn(inter.data[,unique(as.character(treatment))],2))->coms
as.data.table(coms)->coms

apply(coms,1,function(x)
{
if(x[2]=='t8') x<-rev(x)
wilcox.test(x=inter.data[treatment==x[1],outcome],y=inter.data[treatment==x[2],outcome])->inter.test
data.table(g1=x[1],g2=x[2],statistic=inter.test$statistic,p=inter.test$p.value)
})->coms

rbindlist(coms)->coms

coms<-data.table(zu=ind,coms)
coms[,sig:=fcase(p<=0.1,"*",default='')]
coms
})->kan


rbindlist(kan)->kan


####################1
ind<-1
inter.data<-dat[treatment %in% gg[[ind]]]
inter.data[,treatment:=ordered(treatment,levels=gg[[ind]])]

kan[zu==ind & sig=='*']->sig.pairs
as.list(transpose(sig.pairs[,.(g1,g2)]))->sig.pairs

inter.data[,.(mean=mean(outcome),sd=sd(outcome)),by=.(treatment)]->sta

p1<-ggbetweenstats(data=inter.data,
               x=treatment,
               y=outcome,
               xlab='a',
               ylab='Ratio',
			   bf.message=F,
			   point.args=my.points.arg,
			   results.subtitle=F,
			   pairwise.comparisons=F,
			   plot.type='violin',
			   boxplot.args=list(color=NA,fill=NA),
			   centrality.label.args=list(color='transparent',fill='transparent'),
			   centrality.point.args=list(shape=18,size=8,color='darkred')
               )+
			   #geom_signif(comparisons = sig.pairs,y_position=5.3,map_signif_level=function(x) paste('pv= ',sprintf("%4.3f",x)))+
			   geom_signif(comparisons = sig.pairs,y_position=c(5.3),annotations ="")+
			   annotate('text',x=1.5,y=5.8,label=TeX(R"($\textit{p}<0.01$)"))+
               ggplot2::scale_color_manual(values=col16[gg[[ind]]])+
			   ggplot2::scale_y_continuous(breaks=seq(0,6,by=2),limits=c(-0.6,6),expand=expansion(c(0.05,0)))+
			   geom_errorbar(data=sta,mapping=aes(x=treatment,y=mean,ymin=mean-sd,ymax=mean+sd),inherit.aes=F,width=0.05)+
			   theme(axis.text.x=element_text(family='sung',size=9))



###########2
ind<-2
inter.data<-dat[treatment %in% gg[[ind]]]
inter.data[,treatment:=ordered(treatment,levels=gg[[ind]])]

kan[zu==ind & sig=='*']->sig.pairs
as.list(transpose(sig.pairs[,.(g1,g2)]))->sig.pairs
inter.data[,.(mean=mean(outcome),sd=sd(outcome)),by=.(treatment)]->sta



library(latex2exp)

p2<-ggbetweenstats(data=inter.data,
               x=treatment,
               y=outcome,
               xlab='b',
               ylab='Ratio',
			   bf.message=F,
			   point.args=my.points.arg,
			   results.subtitle=F,
			   pairwise.comparisons=F,
			   plot.type='violin',
			   boxplot.args=list(color=NA,fill=NA),
			   centrality.label.args=list(color='transparent',fill='transparent'),
			   centrality.point.args=list(shape=18,size=8,color='darkred')
               )+
               #geom_signif(comparisons = sig.pairs,y_position=c(5.3),map_signif_level=function(x) paste('pv= ',sprintf("%4.3f",x)))+
			   geom_signif(comparisons = sig.pairs,y_position=c(5.3),annotations ="")+
			   annotate('text',x=1.5,y=5.8,label=TeX(R"($\textit{p}<0.01$)"))+
               ggplot2::scale_color_manual(values=col16[gg[[ind]]])+
			   ggplot2::scale_y_continuous(breaks=seq(0,6,by=2),limits=c(-0.6,6),expand=expansion(c(0.05,0)))+
			   geom_errorbar(data=sta,mapping=aes(x=treatment,y=mean,ymin=mean-sd,ymax=mean+sd),inherit.aes=F,width=0.05)+
			   theme(axis.text.x=element_text(family='sung',size=9))

####
library(patchwork)
library(svglite)

svglite('figA1.svg',width=8.5,height=4.7)
p1+p2+plot_layout(nrow=1)

dev.off()
####

