温馨提示:本文翻译自stackoverflow.com,查看原文请点击:r - How to set background color for each plot in a facet grid using numeric values

r - 如何使用数值为构面网格中的每个图设置背景色

发布于 2020-03-27 11:35:10

我想给每个图的背景上色以突出相关性。整个想法是几个时间序列的自相关矩阵图。

之后,只要您能通过我的超级简化示例轻松理解,我几乎可以正常工作:

library(tidyverse)
set.seed(214)

n <- 1000
df <- tibble(v1 = runif(n), v2 = runif(n)*0.1 + v1, v3 = runif(n)*0.2 + v2, v4 = runif(n)*0.3 + v3, v5 = runif(n)*0.4 + v4, v6 = runif(n)*0.5 + v5)

C                   <- crossing(w1 = 1:length(df), w2 = 1:length(df))    # Alle Kombinationsmöglichkeiten
CM                  <- array(0, dim = c(length(df), length(df)))   #Correlation Matrix

FACET_LIST <- lapply(1:nrow(C), function(c) { # c <- 14   C[c,]
  tibble(a1 = unlist(df[, C$w1[c]], use.names = FALSE), 
         a2 = unlist(df[, C$w2[c]], use.names = FALSE), 
         name1 = names(df[, C$w1[c]]),
         name2 = names(df[, C$w2[c]])
  )
})

FACET <- do.call(rbind.data.frame, FACET_LIST)

FACET$name1 <- as_factor(FACET$name1)
FACET$name2 <- as_factor(FACET$name2)

for (i in seq_along(df)) {
  for (j in seq_along(df)) {
    CM[i,j] <- cor(df[i], df[j], use = "complete.obs")
  }
}

dat_text <- data.frame(
  name1 = rep(names(df), each = length(names(df))), 
  name2 = rep(names(df), length(names(df))), 
  R2 = paste(round(as.vector(CM) * 100, 1), "%")
)

p <- ggplot()
p <- p + geom_point(data=FACET, aes(a1, a2), size = 0.5)
p <- p + stat_smooth(data=FACET, aes(a1, a2), method = "lm")
p <- p + facet_grid(vars(name1), vars(name2)) + coord_fixed()
p <- p + geom_rect(data = dat_text, aes(fill = R2), xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, alpha = 0.3)
p <- p + geom_text(data = dat_text, aes(x = 0.3, y = 1.2, label = R2))
p <- p + scale_fill_brewer(palette = "Greens")

p

我正在寻找最后一行。它总是为我提供默认颜色。

编辑:

代码已更新;我主要具有很强的相关性,但我希望色标的范围从0%-100%。现在是这样的: 在此处输入图片说明

查看更多

查看更多

提问者
Pelle
被浏览
18
Pelle 2019-07-04 20:32

因此,在您的帮助下,我找到了解决方案。首先,该dat_text$R2列必须为原因数字。添加%符号会将其转换为字符,该字符被解释为离散比例。

dat_text <- tibble(
  name1 = rep(names(df), each = length(names(df))), 
  name2 = rep(names(df), length(names(df))), 
  R2 = round(as.vector(CM) * 100, 1)
)

可以在geom_text通话中添加百分号然后,该scale_fill_gradient呼叫工作正常。我找不到将比例从0%固定为100%的方法,但最终可能会更好。否则,背景颜色之间几乎没有区别。

p <- ggplot()
p <- p + geom_point(data=FACET, aes(a1, a2), size = 0.5)
p <- p + stat_smooth(data=FACET, aes(a1, a2), method = "lm")
p <- p + facet_grid(vars(name1), vars(name2)) + coord_fixed()
p <- p + geom_rect(data = dat_text, aes(fill = R2), xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, alpha = 0.3)
p <- p + geom_text(data = dat_text, aes(x = 0.3, y = 1.2, label = paste0(R2,"%")))
p <- p + scale_fill_gradient(low = "black", high = "darkgreen", aesthetics = "fill")
p

这就是我的最终图表: 也许我会使用更强的色彩

发布
问题

分享
好友

手机
浏览

扫码手机浏览