如何去除ggplot离散变量修改版雨云图的轴侧空白区域
解决ggplot雨云图离散轴空白区域问题
你遇到的问题是使用ggplot绘制含离散变量的雨云图时,large类别与轴之间存在空白,且scale_x_discrete无效。这是因为coord_flip()交换了x、y轴,原本的离散变量category对应到了y轴,而非x轴。
问题复现代码
# Prepare data sample_data <- iris %>% filter(Species == "setosa" | Species == "virginica") %>% mutate(category = case_when(Sepal.Length > 5 ~ "large", Sepal.Length <= 5 ~ "small")) %>% select(Sepal.Width, Species, category) # Figure ggplot(data = sample_data) + aes(x = category, y = Sepal.Width, fill = category) + ggdist::stat_halfeye( adjust = 0.5, justification = -.1, .width = 0, point_colour = NA ) + geom_boxplot(width = .05, outlier.colour = NA, alpha = 0.5) + ggdist::stat_dots( side = "left", justification = 1.1, binwidth = 0.015) + facet_grid(~ Species) + labs(title = "Figure 1: Change in sepal width with sepal length", x = "Sepal length") + coord_flip() + tidyquant::scale_fill_tq() + tidyquant::theme_tq()
问题图示

解决方案
核心是调整y轴(原x轴)的离散刻度扩展参数,同时微调图形元素的位置避免截断:
- 使用
scale_y_discrete(expand = c(0, 0.05))消除离散轴的默认空白,0.05是为了保留少量空隙,防止图形元素被轴截断; - 调整
stat_halfeye和stat_dots的justification参数,让图形元素更贴近轴。
修改后的完整代码:
# Prepare data sample_data <- iris %>% filter(Species == "setosa" | Species == "virginica") %>% mutate(category = case_when(Sepal.Length > 5 ~ "large", Sepal.Length <= 5 ~ "small")) %>% select(Sepal.Width, Species, category) # Figure ggplot(data = sample_data) + aes(x = category, y = Sepal.Width, fill = category) + ggdist::stat_halfeye( adjust = 0.5, justification = 0, # 调整为0让半眼图贴近轴 .width = 0, point_colour = NA ) + geom_boxplot(width = .05, outlier.colour = NA, alpha = 0.5) + ggdist::stat_dots( side = "left", justification = 1.0, # 同步调整点的位置 binwidth = 0.015) + facet_grid(~ Species) + labs(title = "Figure 1: Change in sepal width with sepal length", x = "Sepal length") + coord_flip() + scale_y_discrete(expand = c(0, 0.05)) + # 消除离散轴空白 tidyquant::scale_fill_tq() + tidyquant::theme_tq()
原理说明
coord_flip()会交换x和y轴的映射关系,原本的离散变量category从x轴转移到了y轴。之前使用scale_x_discrete修改的是翻转后的数值轴(原y轴),自然无法消除离散轴的空白。通过scale_y_discrete调整离散轴的expand参数,就能去掉默认的空白padding。
内容的提问来源于stack exchange,提问作者Tory
相关产品推荐
相关产品推荐

