我想制作一个上三角和下三角具有不同颜色的热图。这正如我所期望的那样:
library(ggnewscale)
library(ggplot2)
library(dplyr)
data <- data.frame(
Var1 = c("b", "c", "a", "c", "a", "b"),
Var2 = c("a", "a", "b", "b", "c", "c"),
val = c(-2.1113581, 0.6189813, -0.4770620, 0.8119133, -0.4029937, 0.7977290)
)
plot_data = data %>%
mutate(triangle = ifelse(Var1 < Var2, "Lower", "Upper")) %>%
group_split(triangle)
ggplot() +
geom_tile(data=plot_data[[1]], aes(x=Var1, y=Var2, fill=val)) +
scale_fill_gradient(low = "lightblue", high = "blue", name = "Upper Values") +
new_scale_fill() + # Part of ggnewscale, allows multiple fill scales
# Lower triangle heatmap with a green color scale
geom_tile(data = plot_data[[2]], aes(x=Var1, y=Var2, fill=val)) +
scale_fill_gradient(low = "lightgreen", high = "darkgreen", name = "Lower Values")
但是,当我尝试对轴进行排序时,它最终会切换三角形中的一些颜色,即 Var1 = b 和 Var2 = a 现在是蓝色而不是绿色:
ggplot() +
geom_tile(data=plot_data[[1]], aes(x=Var1, y=Var2, fill=val)) +
scale_fill_gradient(low = "lightblue", high = "blue", name = "Upper Values") +
new_scale_fill() + # Part of ggnewscale, allows multiple fill scales
# Lower triangle heatmap with a green color scale
geom_tile(data = plot_data[[2]], aes(x=Var1, y=Var2, fill=val)) +
scale_fill_gradient(low = "lightgreen", high = "darkgreen", name = "Lower Values") +
scale_x_discrete(limits = c("b", "a", "c")) +
scale_y_discrete(limits = c("b", "a", "c"))
如何在上三角形和下三角形中保持正确的颜色并保持因子的特定顺序?
不要通过
limits=
设置顺序,而是将变量转换为具有所需顺序的 factor
(并在 drop=FALSE
中设置 scale_x/y_discrete
)。
library(ggnewscale)
library(ggplot2)
library(dplyr, warn = FALSE)
plot_data <- data %>%
mutate(
Var1 = factor(Var1, c("b", "a", "c")),
Var2 = factor(Var2, c("b", "a", "c"))
) |>
mutate(triangle = ifelse(as.integer(Var1) < as.integer(Var2), "Lower", "Upper")) %>%
group_split(triangle)
ggplot() +
geom_tile(data = plot_data[[1]], aes(x = Var1, y = Var2, fill = val)) +
scale_x_discrete(drop = FALSE) +
scale_y_discrete(drop = FALSE) +
scale_fill_gradient(low = "lightblue", high = "blue", name = "Upper Values") +
new_scale_fill() +
geom_tile(data = plot_data[[2]], aes(x = Var1, y = Var2, fill = val)) +
scale_fill_gradient(low = "lightgreen", high = "darkgreen", name = "Lower Values")