问题是:geom_rect阻止使用ggplot2缩放facet_grid。
我想知道它是否是由两个数据帧中的冲突引起的,但不知道如何解决这个问题。希望你能……
x轴范围因数据而发生变化 geom_rect 图层超出了原始图的范围。规模正在完成预期的工作。
geom_rect
如果您希望为每个构面显示不同的矩形,则将facet变量包含在其中会更清晰 shade ,&只保留行 xmin / xmax 内 每个方面的范围。例如:
shade
xmin
xmax
library(dplyr) shade2 <- shade %>% # add facet-specific x-axis range information from data_1 tidyr::crossing(data_1 %>% group_by(z) %>% summarise(x1 = min(x), x2 = max(x)) %>% ungroup) %>% # filter for rects within each facet's x-axis range group_by(z) %>% filter(xmin >= x1 & xmax <= x2) %>% ungroup() > shade2 # A tibble: 3 x 7 xmin xmax ymin ymax z x1 x2 <dbl> <dbl> <dbl> <dbl> <fct> <dbl> <dbl> 1 2 3 -Inf Inf A 1 10 2 6 8 -Inf Inf A 1 10 3 39 43 -Inf Inf B 21 50
情节:
ggplot(data = data_1, aes(x = x, y = y)) + geom_col(fill = "blue") + # geom_col is equivalent to geom_bar(stat = "identity") geom_rect(data = shade2, inherit.aes = FALSE, mapping = aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), fill = 'red', alpha = 0.2) + facet_grid(.~z, space = "free_x", scales = "free_x")