r - 更改 ggpairs 图中的标签

标签 r

<分区>

我有以下代码:

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

这是输出。 enter image description here 我希望这些组以不同的顺序显示。我可以通过替换数据框组列中的字符串来做到这一点:

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

这按我想要的顺序排列,但标签变为“1-c”、“2-b”、“3-d”,因为我更改了一些值。是否可以将图中的“1-c”、“2-b”、“3-d”分别替换为“c”、“b”、“d”,同时保留新的顺序?或者有其他解决方案吗?

最佳答案

您应该将 group 更改为因子并更改级别,而不是更改值:

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

这样您可以保留值,但会更改它们在 ggplot 中的显示顺序。

关于r - 更改 ggpairs 图中的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67436118/

相关文章:

R:使用函数将新列添加到数据框

r - Packrat:快照与恢复的顺序重要吗?

r - 查找数据框的最近星期一

r msm BLAS/LAPACK 例程 'DGEBAL' 给出了错误代码 -3

r - 在 facet_wrap 条文本中只显示一个变量标签?

r - 在 R 中分配向量的一半

R ggplot2在一个数据框中使用多个geom_bar自定义图例

r - 使用 RSelenium 在 Chrome 中启用 Adblocker 扩展

r - 对 readHTMLTable 解析的因子列进行子集化不返回结果

r - 没有拉伸(stretch)的 Shiny 应用程序的 renderDataTable 中的列宽