【问题标题】:Reorder axis labels of correlation matrix plot [duplicate]重新排序相关矩阵图的轴标签
【发布时间】:2020-01-11 16:16:49
【问题描述】:

我正在使用 ggcorrplot 构建相关矩阵,但输出以我不想要的方式重新排序列。如何对列重新排序?

出于本示例的目的,我将使用在 R 中找到的“mtcars”数据集。生成最终输出后,我需要对列重新排序,因为它会不断重新排序为我不知道的格式想要。

注意:网站提供的代码如下:http://www.sthda.com/english/wiki/ggplot2-quick-correlation-matrix-heatmap-r-software-and-data-visualization

library(ggcorrplot)

mydata <- mtcars

#correlation matrix
cormat <- round(cor(mydata),2)

library(reshape2)
melted_cormat <- melt(cormat)
head(melted_cormat)

library(ggplot2)
ggplot(data = melted_cormat, aes(x=Var1, y=Var2, fill=value)) + 
  geom_tile()

# Get upper triangle of the correlation matrix
get_upper_tri <- function(cormat){
  cormat[lower.tri(cormat)]<- NA
  return(cormat)
}

upper_tri <- get_upper_tri(cormat)

# Melt the correlation matrix
library(reshape2)
melted_cormat <- melt(upper_tri, na.rm = TRUE)
# Heatmap
library(ggplot2)
ggplot(data = melted_cormat, aes(Var2, Var1, fill = value))+
  geom_tile(color = "white")+
  scale_fill_gradient2(low = "blue", high = "red", mid = "white", 
                       midpoint = 0, limit = c(-1,1), space = "Lab", 
                       name="Pearson\nCorrelation") +
  theme_minimal()+ 
  theme(axis.text.x = element_text(angle = 45, vjust = 1, 
                                   size = 12, hjust = 1))+
  coord_fixed()

这是我想要的相关矩阵,但我需要将列重新排序为与所示不同的顺序。

任何帮助都会很棒。谢谢大家!

【问题讨论】:

  • 如果您能说明列的排列方式会很有帮助。

标签: r matrix ggplot2 pearson-correlation ggcorrplot


【解决方案1】:

假设我们希望 x-axis 根据其名称 (labels) 按字母顺序排序,y-axis 相同但顺序相反。以下代码有效(其余代码相同)。

ggplot(data = melted_cormat, aes(reorder(Var2,  -desc(as.character(Var2))), 
                                 reorder(Var1,  desc(as.character(Var1))), fill = value))+
  geom_tile(color = "white")+
  scale_fill_gradient2(low = "blue", high = "red", mid = "white", 
                       midpoint = 0, limit = c(-1,1), space = "Lab", 
                       name="Pearson\nCorrelation") +
  theme_minimal()+ 
  theme(axis.text.x = element_text(angle = 45, vjust = 1, 
                                   size = 12, hjust = 1))+
  coord_fixed()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-17
    • 2017-01-12
    • 2018-03-15
    • 2021-02-13
    • 2021-12-23
    • 2014-07-02
    • 1970-01-01
    • 2014-07-27
    相关资源
    最近更新 更多