3160067d73ab50a596e8f2224fe427a260a0933c
[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 #' @export
12 plot_valse <- function(X, Y, model, n, comp = FALSE, k1 = NA, k2 = NA)
13 {
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 {
24 Melt <- melt(t((model$phi[, , r])))
25 gReg[[r]] <- ggplot(data = Melt, aes(x = Var1, y = Var2, fill = value)) +
26 geom_tile() + scale_fill_gradient2(low = "blue", high = "red", mid = "white",
27 midpoint = 0, space = "Lab") + ggtitle(paste("Regression matrices in cluster", r))
28 }
29 print(gReg)
30
31 ## Differences between two clusters
32 if (comp)
33 {
34 if (is.na(k1) || is.na(k))
35 print("k1 and k2 must be integers, representing the clusters you want to compare")
36 Melt <- melt(t(model$phi[, , k1] - model$phi[, , k2]))
37 gDiff <- ggplot(data = Melt, aes(x = Var1, y = Var2, fill = value))
38 + geom_tile()
39 + scale_fill_gradient2(low = "blue", high = "red", mid = "white", midpoint = 0,
40 space = "Lab")
41 + ggtitle(paste("Difference between regression matrices in cluster",
42 k1, "and", k2))
43 print(gDiff)
44 }
45
46 ### Covariance matrices
47 matCov <- matrix(NA, nrow = dim(model$rho[, , 1])[1], ncol = K)
48 for (r in 1:K)
49 matCov[, r] <- diag(model$rho[, , r])
50 MeltCov <- melt(matCov)
51 gCov <- ggplot(data = MeltCov, aes(x = Var1, y = Var2, fill = value)) + geom_tile()
52 + scale_fill_gradient2(low = "blue", high = "red", mid = "white", midpoint = 0,
53 space = "Lab")
54 + ggtitle("Covariance matrices")
55 print(gCov)
56
57 ### Proportions
58 gam2 <- matrix(NA, ncol = K, nrow = n)
59 for (i in 1:n)
60 gam2[i, ] <- c(model$proba[i, model$affec[i]], model$affec[i])
61
62 bp <- ggplot(data.frame(gam2), aes(x = X2, y = X1, color = X2, group = X2))
63 + geom_boxplot()
64 + theme(legend.position = "none")
65 + background_grid(major = "xy", minor = "none")
66 print(bp)
67
68 ### Mean in each cluster
69 XY <- cbind(X, Y)
70 XY_class <- list()
71 meanPerClass <- matrix(0, ncol = K, nrow = dim(XY)[2])
72 for (r in 1:K)
73 {
74 XY_class[[r]] <- XY[model$affec == r, ]
75 if (sum(model$affec == r) == 1) {
76 meanPerClass[, r] <- XY_class[[r]]
77 } else {
78 meanPerClass[, r] <- apply(XY_class[[r]], 2, mean)
79 }
80 }
81 data <- data.frame(mean = as.vector(meanPerClass),
82 cluster = as.character(rep(1:K, each = dim(XY)[2])), time = rep(1:dim(XY)[2], K))
83 g <- ggplot(data, aes(x = time, y = mean, group = cluster, color = cluster))
84 print(g + geom_line(aes(linetype = cluster, color = cluster))
85 + geom_point(aes(color = cluster)) + ggtitle("Mean per cluster"))
86 }