fix few things
[valse.git] / pkg / R / plot_valse.R
1 #' Plot
2 #'
3 #' It is a function which plots relevant parameters
4 #'
5 #' @param X matrix of covariates (of size n*p)
6 #' @param Y matrix of responses (of size n*m)
7 #' @param model the model constructed by valse procedure
8 #' @param n sample size
9 #' @return several plots
10 #'
11 #' @examples TODO
12 #'
13 #' @export
14 #'
15 plot_valse = function(X,Y,model,n, comp = FALSE, k1 = NA, k2 = NA){
16 require("gridExtra")
17 require("ggplot2")
18 require("reshape2")
19 require("cowplot")
20
21 K = length(model$pi)
22 ## regression matrices
23 gReg = list()
24 for (r in 1:K){
25 Melt = melt(t((model$phi[,,r])))
26 gReg[[r]] = ggplot(data = Melt, aes(x=Var1, y=Var2, fill=value)) + geom_tile() +
27 scale_fill_gradient2(low = "blue", high = "red", mid = "white", midpoint = 0, space = "Lab") +
28 ggtitle(paste("Regression matrices in cluster",r))
29 }
30 print(gReg)
31
32 ## Differences between two clusters
33 if (comp){
34 if (is.na(k1) || is.na(k)){print('k1 and k2 must be integers, representing the clusters you want to compare')}
35 Melt = melt(t(model$phi[,,k1]-model$phi[,,k2]))
36 gDiff = ggplot(data = Melt, aes(x=Var1, y=Var2, fill=value)) + geom_tile() +
37 scale_fill_gradient2(low = "blue", high = "red", mid = "white", midpoint = 0, space = "Lab") +
38 ggtitle(paste("Difference between regression matrices in cluster",k1, "and", k2))
39 print(gDiff)
40
41 }
42
43 ### Covariance matrices
44 matCov = matrix(NA, nrow = dim(model$rho[,,1])[1], ncol = K)
45 for (r in 1:K){
46 matCov[,r] = diag(model$rho[,,r])
47 }
48 MeltCov = melt(matCov)
49 gCov = ggplot(data =MeltCov, aes(x=Var1, y=Var2, fill=value)) + geom_tile() +
50 scale_fill_gradient2(low = "blue", high = "red", mid = "white", midpoint = 0, space = "Lab") +
51 ggtitle("Covariance matrices")
52 print(gCov )
53
54 ### Proportions
55 gam2 = matrix(NA, ncol = K, nrow = n)
56 for (i in 1:n){
57 gam2[i, ] = c(model$proba[i, model$affec[i]], model$affec[i])
58 }
59
60 bp <- ggplot(data.frame(gam2), aes(x=X2, y=X1, color=X2, group = X2)) +
61 geom_boxplot() + theme(legend.position = "none")+ background_grid(major = "xy", minor = "none")
62 print(bp)
63
64 ### Mean in each cluster
65 XY = cbind(X,Y)
66 XY_class= list()
67 meanPerClass= matrix(0, ncol = K, nrow = dim(XY)[2])
68 for (r in 1:K){
69 XY_class[[r]] = XY[model$affec == r, ]
70 if (sum(model$affec==r) == 1){
71 meanPerClass[,r] = XY_class[[r]]
72 } else {
73 meanPerClass[,r] = apply(XY_class[[r]], 2, mean)
74 }
75 }
76 data = data.frame(mean = as.vector(meanPerClass), cluster = as.character(rep(1:K, each = dim(XY)[2])), time = rep(1:dim(XY)[2],K))
77 g = ggplot(data, aes(x=time, y = mean, group = cluster, color = cluster))
78 print(g + geom_line(aes(linetype=cluster, color=cluster))+ geom_point(aes(color=cluster)) + ggtitle('Mean per cluster'))
79
80 }