使用热图反映相关数据帧之间的差异并仅显示下三角

Using a heatmap to reflect differences between correlation dataframes and displaying only lower triangle

我有上面的热图,是我使用以下方法生成的:

heat_map <- ggplot(melt_p4, aes(Var1, Var2)) +
  geom_tile(aes(fill = value), color = "white") +
  labs(title = "ST - LT Correlation Across Factor") +
  scale_fill_gradient(low = "red", high = "green") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  geom_text(aes(label = round(value, 1)), size = 2.2)

其中 melt_p4 是

melt_p4 <- melt(p4)

p4 是

p4 <- correlations_3months - correlations_history

哪里

correlations_3months <- round(cor(Raw_Index_3months_xts_Returns[-1,]),2)
correlations_history <- round(cor(Raw_Index_History_xts_Returns[-1,]),2)

热图基本上是一个从短期相关数据帧中减去长期相关数据帧的数据帧。因此,我想知道是否有一个参数可以与热图一起使用,以便仅显示下方三角形(在所有 0 的对角线下方)。否则,我会在热图的上半部分和下半部分得到一个镜像。这可能吗?

也希望我已经为这个问题提供了足够的代码。

如果p4是一个矩阵,你可以使用upper.tri作为:

p4[upper.tri(p4)] <- NA
melt_p4 <- melt(p4)
melt_p4 <- melt_p4[!is.na(melt_p4$value),]

colnames(melt_p4) <- c("Var1", "Var2", "value")

ggplot(melt_p4, aes(Var1, Var2)) +
  geom_tile(aes(fill = value), color = "white") +
  labs(title = "ST - LT Correlation Across Factor") +
  scale_fill_gradient(low = "red", high = "green") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  geom_text(aes(label = round(value, 1)), size = 2.2) +
  theme_bw() +
  scale_x_discrete(expand=c(0,0)) + 
  scale_y_discrete(expand=c(0,0)) 

示例数据

set.seed(1)
p4 <- matrix(runif(16, 0, 1), nrow = 4, ncol = 4)

row.names(p4) <- c("A", "B", "C", "D")
colnames(p4) <- c("A", "B", "C", "D")