如何在geom_density_ridges2中将X轴扩展至0且不偏移图形
解决ggridges扩展X轴范围后图形偏移的问题
你碰到的问题根源是,直接给X轴加limits后,stat="binline"和geom_text的分箱统计没对齐新的X轴范围,导致图形偏移。解决办法是给分箱统计指定从0开始的边界,同时扩展X轴范围,修改后的完整代码如下:
library(tidyverse) library(ggridges) df <- structure(list(id = c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29), item = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"), class = "factor"), value = c(8, 9, 4, 5, 8, 9, 7, 9, 8, 8, 7, 6, 9, 8, 9, 9, 9, 9, 8, 9, 9, 9, 8, 9, 8, 8, 7, 8, 8, 8, 7, 9, 8, 9, 8, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 7, 9, 9, 8, 9, 8, 9, 7, 9, 7, 7, 7, 8)), row.names = c(NA, -58L), class = c("tbl_df", "tbl", "data.frame")) df %>% ggplot(aes(x = value, y = item, group = item)) + geom_density_ridges2(aes(fill = item), stat = "binline", binwidth = 1, scale = 0.95, boundary = 0) + # 指定分箱从0开始,对齐X轴新范围 geom_text( stat = "bin", aes( y = group + 0.95*stat(count/max(count)), label = ifelse(stat(count) > 0, stat(count), "") ), vjust = -0.5, size = 3, color = "black", binwidth = 1, boundary = 0 # 文本统计用相同分箱边界,避免偏移 ) + scale_x_continuous( breaks = 0:9, limits = c(0,9), # 扩展X轴到0-9 name = "Answer (higher = better)" ) + scale_y_discrete( expand = expansion(add = 2) ) + scale_fill_viridis_d() + labs( title = "Example", y = NULL ) + theme_ridges(grid = FALSE) + theme( axis.title.x = element_text(hjust = 0.5), axis.title.y = element_text(hjust = 0.5), legend.position = "none", plot.title.position = "plot", plot.title = element_text(face="bold") )
核心修改说明:
- 给
geom_density_ridges2和geom_text的分箱统计都加上boundary = 0:让分箱区间从0开始(0-1、1-2……8-9),保证图形和文本的位置与新X轴范围完全对齐,不会偏移。 - 在
scale_x_continuous里添加limits = c(0,9):正式把X轴的范围扩展到0-9,同时保留0到9的刻度。
修改后,X轴会完整显示0到9的刻度,0-3的区间因为没有数据,不会显示柱子和文本,完全符合需求。
内容的提问来源于stack exchange,提问作者Eric Green
相关产品推荐
相关产品推荐

