3

I have the following code:

library(GGally)
group <- c("b", "c", "d", "c", "d", "b", "d", "c", "b", "c", "d", "c", "d", "b", "d", "c")
one <- c(123, 174, 154, 143, 184, 134, 165, 192, 123, 174, 154, 143, 184, 134, 165, 192)
two <- c(223, 274, 254, 243, 284, 234, 265, 292, 223, 274, 254, 243, 284, 234, 265, 292)
three <- c(323, 374, 354, 343, 384, 334, 365, 392, 323, 374, 354, 343, 384, 334, 365, 392)
four <- c(423, 474, 454, 443, 484, 434, 465, 492, 423, 474, 454, 443, 484, 434, 465, 492)
df <- data.frame(group, one, two, three, four)
p <- df %>% ggpairs(.,
                    mapping = ggplot2::aes(colour=group),
                    lower = list(continuous = wrap("smooth")),
                    diag = list(continuous = wrap("blankDiag"))
)
getPlot(p, 1, 5) + guides(fill=FALSE)
plots = list()
for (i in 1:5){
  plots <- c(plots, lapply(2:p$ncol, function(j) getPlot(p, i = i, j = j)))
}  
p <- ggmatrix(plots, 
              nrow = 5,
              ncol=p$ncol-1, 
              xAxisLabels = p$xAxisLabels[2:p$ncol], 
              yAxisLabels = p$yAxisLabels, 
)
p

This is the output. enter image description here I want the groups to be shown in a different order. I can do this by replacing the strings in the group column of the dataframe:

df$group = str_replace_all(df$group,"b","2-b")
df$group = str_replace_all(df$group,"c","1-c")
df$group = str_replace_all(df$group,"d","3-d")

enter image description here

That puts things in the order I want, but the labels become "1-c", "2-b", "3-d" because I've changed some of the values. Is it possible to replace "1-c", "2-b", "3-d" with "c", "b", "d" respectively in the plot, while retaining the new order? Or is there another solution?

Gareth Walker
  • 211
  • 2
  • 6

2 Answers2

2

You can manually specify the order you want like this:

df$group <- factor(df$group, levels = c("c", "b", "d"))

Which gives this, which I think is what you want:

enter image description here

Leonardo Viotti
  • 476
  • 1
  • 5
  • 15
2

Instead of changing the values, you should change group to factor and change the levels:

df$group = factor(df$group, levels = c("c","b","d"))

# the rest is unchanged:
p <- df %>% ggpairs(.,
                    mapping = ggplot2::aes(colour=group),
                    lower = list(continuous = wrap("smooth")),
                    diag = list(continuous = wrap("blankDiag"))
)
getPlot(p, 1, 5) + guides(fill=FALSE)
plots = list()
for (i in 1:5){
  plots <- c(plots, lapply(2:p$ncol, function(j) getPlot(p, i = i, j = j)))
}  
p <- ggmatrix(plots, 
              nrow = 5,
              ncol=p$ncol-1, 
              xAxisLabels = p$xAxisLabels[2:p$ncol], 
              yAxisLabels = p$yAxisLabels, 
)
p

enter image description here

This way you preserve the values, but change the order in which they appear in ggplot.

VitaminB16
  • 1,174
  • 1
  • 3
  • 17