我正在ggplot中制作如下的tilemap。 2个问题:
1)如何扩展x轴限制以将组标记为x = 4? 2)如何自动在组之间放置水平线(即1和2、2和3等之间的线),而不是手动指定y值?
require(tidyverse)
set.seed(1)
df <- data.frame(ID = as.character(c(1:50)),
Group = sample(1:8, 50, replace = T),
var1 = sample(c('Y', 'N'), 50, replace = T),
var2 = sample(c('Y', 'N'), 50, replace = T),
var3 = sample(c('Y', 'N'), 50, replace = T)) %>%
gather('var', 'y_n', var1:var3) %>%
arrange(-Group) %>%
mutate(ID = factor(ID, levels = unique(ID, ordered = T)))
ggplot(df, aes(var, ID, label = Group))+
geom_tile(aes(fill = y_n), color = 'white')+
scale_fill_manual(values = c('white', 'lightblue'))+
scale_x_discrete(expand = c(0, 0))+
geom_text(x = 3.5, hjust = 'right')
答案 0 :(得分:3)
使用构面可以解决您的两个问题:如果您用Group
进行构面,则可以编辑构面面板以在每个组周围指定黑色边框,它将自动在绘图区域之外标记每个组。
ggplot(df, aes(var, ID, label = Group)) +
geom_tile(aes(fill = y_n), color = 'white') +
scale_fill_manual(values = c('white', 'lightblue')) +
scale_x_discrete(expand = c(0, 0)) +
facet_grid(Group~., scales = "free", space = "free") + #facet by group
theme(strip.background = element_blank(), #remove background for facet labels
panel.border = element_rect(colour = "black", fill = NA), #add black border
panel.spacing = unit(0, "lines")) #remove space between facets
在facet_grid()
内,重要的是添加scales = "free"
,以便每个构面仅具有该组的y值,然后添加space = free
,以便根据如何调整每个组的大小它具有许多y值。
答案 1 :(得分:2)
您可以尝试使用geom_hline
方法。还添加了垂直线,以进行脱模。
# calculate the group numbers
gr <- df %>%
group_by(Group) %>%
summarise(n=length(unique(ID))) %>%
arrange(-Group) %>%
mutate(nn=cumsum(n))
ggplot(df, aes(var, ID, label = Group))+
geom_tile(aes(fill = y_n), color = 'white')+
scale_fill_manual(values = c('white', 'lightblue'))+
scale_x_discrete(expand = c(0, 0))+
geom_text(x = 3.5, hjust = 'right') +
geom_vline(xintercept = 1:length(unique(df$var))+0.5)+
geom_hline(yintercept = gr$nn+0.5)