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