我正在使用ggcorrplot构建相关矩阵,但输出会按一种我不想要的方式重新排序列。如何重新排序列?
为了举例说明,我将使用R中的“mtcars”数据集。在最终输出结果后,我需要重新排序列,因为它会按照我不想要的格式重新排序。
注意:代码提供网址如下:http://www.sthda.com/english/wiki/ggplot2-quick-correlation-matrix-heatmap-r-software-and-data-visualization
为了举例说明,我将使用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()
这是我想要的相关矩阵,但我需要重新排序列的顺序,使其不同于所示的顺序。
任何帮助都将是极好的。谢谢大家!