ggplot分面内按分组分离geom_linerange解决线条重叠问题
解决方案
核心思路是通过ggplot内置的位置避让功能,让同一condition1分组下不同condition2的图形元素在y轴方向自动错开,不需要修改原始数据,是官方推荐的最优实现方案。
原代码重叠的原因是同一condition1下的所有元素y轴坐标完全一致,使用position_dodge无需手动调整原始数据的y值,自动完成位置偏移。
修改后完整代码
test = read.table(text = 'condition1 condition2 estimate std_error name a x .466 .09 name_1 a y .343 .131 name_1 b x .466 .09 name_1 b y .343 .131 name_1 a x .466 .09 name_2 a y .343 .131 name_2 b x .466 .09 name_2 b y .343 .131 name_2', header = T, stringsAsFactors = T) # 定义统一的避让规则,保证点和误差线对齐 pd <- position_dodge(width = 0.2) ggplot(data = test, aes(x = estimate, y = condition1, fill = condition2, group = condition2)) + geom_point(color = 'black', position = pd) + geom_linerange(aes(xmin = estimate - std_error, xmax = estimate + std_error), color = 'black', position = pd) + ylab(NULL) + facet_grid(name ~ ., scales = "free_y", space = "free_y", switch = 'y')
参数说明
position_dodge(width = 0.2)中的width参数控制错开的距离,可根据实际展示需求调整,数值越大两组元素的错开距离越远- 必须将同一个
position_dodge对象同时应用到geom_point和geom_linerange,否则会出现点和误差线不对齐的问题
原问题效果示意图:
内容的提问来源于stack exchange,提问作者Parseltongue
相关产品推荐
相关产品推荐

