I am making a correlation matrix with geom_tile() with some data that has relatively mild correlations, so I am attempting to rescale the coloring simply by filtering out the perfect correlations. When I do this, the perfect correlation tiles are colored white--is there a way to change this color? I'd prefer it to be gray or black.
And if there's some much easier way to accomplish my overall goal, I'm happy to try something else entirely!
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())
If I understand correctly, we could do something like this:
We create a new column fill_value
that replaces perfect correlations with NA
;
then any NA
in fill_value
(i.e., where value
= 1) is colored 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()
)