代码之家  ›  专栏  ›  技术社区  ›  a_todd12

ggplot相关矩阵中的颜色完美相关图块

  •  1
  • a_todd12  · 技术社区  · 4 月前

    我正在用geom_tile()和一些相关性相对较弱的数据制作一个相关性矩阵,所以我试图通过过滤掉完美的相关性来重新缩放颜色。当我这样做的时候,完美的相关性图块是白色的——有办法改变这种颜色吗?我更喜欢灰色或黑色。

    如果有更简单的方法来实现我的总体目标,我很乐意尝试完全不同的方法!

    cor_melt <- structure(list(Var1 = c("year", "year", "year", "year", "year", 
    "white", "white", "white", "white", "white", "mother_dropout_age22", 
    "mother_dropout_age22", "mother_dropout_age22", "mother_dropout_age22", 
    "mother_dropout_age22", "mother_married", "mother_married", "mother_married", 
    "mother_married", "mother_married", "childbpi_std", "childbpi_std", 
    "childbpi_std", "childbpi_std", "childbpi_std"), Var2 = c("year", 
    "white", "mother_dropout_age22", "mother_married", "childbpi_std", 
    "year", "white", "mother_dropout_age22", "mother_married", "childbpi_std", 
    "year", "white", "mother_dropout_age22", "mother_married", "childbpi_std", 
    "year", "white", "mother_dropout_age22", "mother_married", "childbpi_std", 
    "year", "white", "mother_dropout_age22", "mother_married", "childbpi_std"
    ), value = c(1, 0.0593362305873463, -0.0820151460829019, 0.0598390369200811, 
    -0.0676470633577078, 0.0593362305873463, 1, -0.242532002168163, 
    0.304707579844858, 0.0106313307599808, -0.0820151460829019, -0.242532002168163, 
    1, -0.192318153843863, 0.0777997496636195, 0.0598390369200811, 
    0.304707579844858, -0.192318153843863, 1, -0.147931969127727, 
    -0.0676470633577078, 0.0106313307599808, 0.0777997496636195, 
    -0.147931969127727, 1)), row.names = c(NA, -25L), class = c("tbl_df", 
    "tbl", "data.frame"))
    
    cor_melt %>% filter(value != 1) %>% 
    ggplot(., aes(x = Var1, y = Var2, fill = value)) +
      geom_tile() +
      scale_fill_gradient2(low = "dodgerblue3", mid = "white", high = "firebrick3", midpoint = 0) +
      labs(x = NULL, y = NULL) +
      theme_minimal() +
      theme(axis.text.x = element_text(angle = 45, hjust = 1.1),
            panel.grid = element_blank())
    
    1 回复  |  直到 4 月前
        1
  •  2
  •   TarJae    4 月前

    如果我理解正确,我们可以这样做:

    我们创建一个新专栏 fill_value 这取代了完美的相关性 NA ; 那么任何 NA 在里面 fill_value (即,在哪里 value =1)是彩色的 grey50

      
    library(dplyr)
    library(ggplot2)
      
    cor_melt %>%
      mutate(fill_value = ifelse(value == 1, NA, value)) |> 
      ggplot(aes(x = Var1, y = Var2, fill = fill_value)) +
        geom_tile() +
        scale_fill_gradient2(
          low = "dodgerblue3", mid = "white", high = "firebrick3", midpoint = 0, na.value = "grey50") +
        theme_minimal() +
        labs(x = NULL, y = NULL) +
        theme(
          axis.text.x = element_text(angle = 45, hjust = 1.1),
          panel.grid  = element_blank()
        )
    

    enter image description here