man*_*ndy 3 r colors heatmap ggplot2
我正在尝试在 ggplot 中生成热图。我希望每个组都有不同的颜色渐变,但不知道该怎么做。我当前的代码如下所示:
## dummy data -----------------------------------------------------------------------------
data <- data.frame(
group = sample(c("Direct Patient Care", "Indirect Patient Care", "Education", "Rounds", "Handoff", "Misce"), 30, replace = T),
pct = rnorm(30, mean = 50, sd = 8)
)
## generate group id
data <- data %>%
group_by(group) %>%
mutate(id = row_number())
data$grpid <- with(data, ifelse(group == "Direct Patient Care", 1, ifelse(group == "Indirect Patient Care", 2,
ifelse(group == "Education", 3,
ifelse(group == "Rounds", 4,
ifelse(group == "Handoff", 5,6 ))))))
## draw graph ------------------------------------------------------------------------------
library(ggplot2)
p <- ggplot(data, aes(x=id, y=group, fill = pct)) +
theme(panel.background = element_rect(fill = "white", colour = "grey50"), aspect.ratio = 0.4) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank()
)+
# guides(fill = guide_legend("Time, %")) +
geom_tile() +
scale_x_continuous (name = " ", breaks = seq(1, 8, by = 1)) +
scale_y_discrete(name = " ") +
theme(axis.text.x = element_text(angle = 0,hjust = 1,vjust = 1), plot.title = element_text(hjust = 0.5) ) +
ggtitle("Heatmap of time spent doing activities across 194 shifts")
p + scale_fill_gradient2(low = "white", high = "red", limits = c(0, 80), breaks = c(0, 10, 20, 30, 40, 50, 60, 70), guide = guide_legend("Time, %")) ## change the color theme ##
Run Code Online (Sandbox Code Playgroud)
如何更改每个组的颜色主题,例如“轮次”为红色,“杂项”为蓝色,“Handoff”为绿色等...
非常感谢!
您可以通过在数据中创建自己的重新缩放值,然后稍微“修改”alpha美学与美学相结合来做到这一点fill:
library(tidyverse)
data %>%
group_by(group) %>%
mutate(rescale = scales::rescale(pct)) %>%
ggplot(., aes(x = factor(id), y = group)) +
geom_tile(aes(alpha = rescale, fill = group), color = "white") +
scale_alpha(range = c(0.1, 1))
Run Code Online (Sandbox Code Playgroud)
首先,我们创建一个名为新列rescale,其rescales在pct从0到1,那么你逼scale_alpha(range = c(0, 1))[注,在这种情况下,我使用的c(0.1, 1),这样你仍然可以“看”到零点。
最后,您可能想要删除指南:
data %>%
group_by(group) %>%
mutate(rescale = scales::rescale(pct)) %>%
ggplot(., aes(x = factor(id), y = group)) +
geom_tile(aes(alpha = rescale, fill = group), color = "white") +
scale_alpha(range = c(0.1, 1)) +
theme(legend.position = "none")
Run Code Online (Sandbox Code Playgroud)
注意,通过使用aes(x = factor(id)...您可以绕过手动设置,x-axis因为在这种情况下,您似乎希望将其视为一个因素而不是数字标度。
最后,如果你真的想要花哨,你可以将axis.text.y颜色双重编码为你的factor(即,data$group)变量的级别:
data %>%
group_by(group) %>%
mutate(rescale = scales::rescale(pct)) %>%
ggplot(., aes(x = factor(id), y = group)) +
geom_tile(aes(alpha = rescale, fill = group), color = "white") +
scale_alpha(range = c(0.1, 1)) +
theme(legend.position = "none",
axis.text.y = element_text(color = scales::hue_pal()(length(levels(data$group)))),
axis.ticks = element_blank()) +
labs(x = "", y = "")
Run Code Online (Sandbox Code Playgroud)