有两个选项可供考虑,都使用辅助轴来模拟右侧的面板边框。如果您也想取消顶部的分面框轮廓,请使用选项 2。
选项 1:
ggplot(df,
aes(x = Month, y = Abundance, fill = Type)) +
geom_col(position = "dodge", colour = "black") +
scale_y_continuous(labels = function(x){paste(x, "-")}, # simulate tick marks for left axis
sec.axis = dup_axis(breaks = 0)) + # add right axis
scale_fill_grey() +
facet_grid(~Season, scales = "free_x", space = "free_x") +
theme_classic() +
theme(axis.title.y.right = element_blank(), # hide right axis title
axis.text.y.right = element_blank(), # hide right axis labels
axis.ticks.y = element_blank(), # hide left/right axis ticks
axis.text.y = element_text(margin = margin(r = 0)), # move left axis labels closer to axis
panel.spacing = unit(0, "mm"), # remove spacing between facets
strip.background = element_rect(size = 0.5)) # match default line size of theme_classic

(我将图例保留在默认位置,因为它在这里并不重要。)
选项 2是选项 1 的修改,移除了小平面轮廓并添加了一条水平线以模拟顶部边框。明确设置 Y 轴范围以匹配此边框的高度:
y.upper.limit <- diff(range(df$Abundance)) * 0.05 + max(df$Abundance)
y.lower.limit <- 0 - diff(range(df$Abundance)) * 0.05
ggplot(df,
aes(x = Month, y = Abundance, fill = Type)) +
geom_col(position = "dodge", colour = "black") +
geom_hline(yintercept = y.upper.limit) +
scale_y_continuous(labels = function(x){paste(x, "-")}, #
sec.axis = dup_axis(breaks = 0), #
expand = c(0, 0)) + # no expansion from explicitly set range
scale_fill_grey() +
facet_grid(~Season, scales = "free_x", space = "free_x") +
coord_cartesian(ylim = c(y.lower.limit, y.upper.limit)) + # set explicit range
theme_classic() +
theme(axis.title.y.right = element_blank(), #
axis.text.y.right = element_blank(), #
axis.ticks.y = element_blank(), #
axis.text.y = element_text(margin = margin(r = 0)), #
panel.spacing = unit(0, "mm"), #
strip.background = element_blank()) # hide facet outline

使用的样本数据:
set.seed(10)
df <- data.frame(
Month = rep(c("Jun 14", "Aug 14", "Oct 14", "Dec 14", "Apr 15", "Jun 15"),
each = 3),
Type = rep(c("Mangrove", "Mudflat", "Fringe"), 6),
Season = rep(c("Dry1", rep("Wet1", 3), rep("Dry2", 2)), each = 3),
Abundance = sample(50:600, 18)
)
df <- df %>%
mutate(Month = factor(Month, levels = c("Jun 14", "Aug 14", "Oct 14",
"Dec 14", "Apr 15", "Jun 15")),
Season = factor(Season, levels = c("Dry1", "Wet1", "Dry2")))
(为了记录,我不认为facet_grid
/facet_wrap
用于此类用例......)