我想要一个带有右侧变量名称的水平树状图来显示相关系数。如果我可以在一些与 ggplot2 相关的包中实现它会很好,因为我希望该图与我的其他图形相似。scale_x_discrete(position="top)
不起作用,因为这样标签就会消失。这些是我到目前为止的结果:
library(ggplot2)
library(dplyr)
library(tidyr)
library(faux)
library(ggdendro)
# data
set.seed(5)
dat <- rnorm_multi(n = 100,
mu = c(0, 20, 20),
sd = c(1, 5, 5),
r = c(0.5, 0.5, 0.25),
varnames = c("A", "B", "C"),
empirical = FALSE)
# make correlation matrix
cor_matrix_before <- cor(dat, method="spearman")
# make dendrogram
tree <- hclust(as.dist(1 - cor_matrix_before**2))
ggdendrogram(tree) +
theme_light() +
theme(text = element_text(size=16)) +
xlab("") +
ylab("Spearmans rho squared") +
scale_y_reverse(breaks=seq(0,1,0.25), labels=rev(seq(0,1,0.25))) +
geom_hline(yintercept=0.7*0.7, col = "red") +
coord_flip()
(我偷了相关变量的准备:https ://cran.r-project.org/web/packages/faux/vignettes/rnorm_multi.html )
但这就是我想要的(只是一个快速的蒙太奇):
编辑:感谢@tjebo,这是我的最终解决方案(我删除了所有不需要的部分,查看他的答案以获得更通用的答案):
tree <- hclust(as.dist(1 - cor_matrix_before**2))
data <- ggdendro::dendro_data(tree)
ggplot() +
geom_blank()+
geom_segment(data = segment(data), aes_string(x = "x", y = "y", xend = "xend", yend = "yend")) +
geom_hline(yintercept=0.7*0.7, col = "red") +
scale_x_continuous(breaks = seq_along(data$labels$label), labels = data$labels$label, position = "top") +
scale_y_reverse(breaks=seq(0,1,0.25), labels=rev(seq(0,1,0.25))) +
coord_flip() +
theme(axis.text.x = element_text(angle = angle, hjust = 1, vjust = 0.5),
axis.text.y = element_text(angle = angle, hjust = 1),
text = element_text(size=16, family="Calibri")) +
ylab("Spearmans rho squared") +
xlab("") +
theme_light()