ggplot2 geom_point中med_type点重叠:如何实现横向并排?
解决ggplot散点图中不同分组点重叠的问题
嗨,我明白你现在的困扰——不同med_type的点挤在垂直方向重叠,没法清晰区分对吧?咱们来把它们改成横向并排的样式,就像箱线图那样:
核心问题分析
你当前的gen_type是数值型变量(1到17),而position_dodge()在连续型x轴上的表现和分类轴差异很大,没法在每个gen_type分组内横向分散不同med_type的点。所以第一步要把gen_type转成分类因子,让x轴变成离散分组。
修改后的代码
ggplot(sum_tra_heterot_m, aes(x = as.factor(gen_type), y = mean_m2)) + # 关键:x转成因子,同时调整position_dodge的width值 geom_point(aes(shape = as.factor(gen_type), color = as.factor(med_type)), size = 2, position = position_dodge(width = 0.6)) + scale_shape_manual(values = c(1:17), name = "Genre_type", breaks = c(1:17), labels = c("hetero woman on top", "hetero Missionary", "hetero Doggy", "hetero Fellation", "hetero Cunnilingus", "homo Fellation", "homo anal sex", "homo Cunnilingus", "lesbian sex", "men masturbation", "woman masturbation", "naked woman", "naked men", "men erection", "kissing", "detail of penetration", "detail of genital")) + scale_color_manual(values = c('#ff0000','#e9ff00', '#32ff00', '#00ffff', '#4300ff', '#ff00fa'), name = "Medium_type", breaks = c(1:6), labels = c("Foto","Sculpture","Painting","Graphic","Shunga","Hentai")) + # 给x轴加上对应标签,和shape图例统一 scale_x_discrete(name = "Genre_type", labels = c("hetero woman on top", "hetero Missionary", "hetero Doggy", "hetero Fellation", "hetero Cunnilingus", "homo Fellation", "homo anal sex", "homo Cunnilingus", "lesbian sex", "men masturbation", "woman masturbation", "naked woman", "naked men", "men erection", "kissing", "detail of penetration", "detail of genital")) + ggtitle("Men - mean_of_evaluation_by_genre&medium_and_type_of_question") + theme(legend.position = "bottom", # 可选:旋转x轴标签避免重叠 axis.text.x = element_text(angle = 45, hjust = 1)) + facet_wrap(~ quest_type, labeller = labeller(quest_type = labeller_names_2))
关键改动说明
- x轴转因子:
x = as.factor(gen_type)把连续的数值型x轴转成离散分类轴,这样每个gen_type会成为独立的分组,position_dodge就能在每个分组内横向分散不同med_type的点。 - 调整position_dodge的width:把width从0.3改成0.6(你可以根据实际效果微调),让不同
med_type的点有足够的横向间距,避免重叠。 - 统一x轴标签:新增
scale_x_discrete给x轴加上和shape图例一致的标签,让图表更易读。 - 可选优化:如果x轴标签太长重叠,可以用
axis.text.x = element_text(angle = 45, hjust = 1)旋转标签。
额外小技巧
如果同一个gen_type+med_type组合有多个观测值(虽然你这里是均值,但万一有重复),可以用position_jitterdodge替代position_dodge,既保留横向并排,又用轻微抖动避免点完全重叠:
position = position_jitterdodge(jitter.width = 0.1, dodge.width = 0.6)
内容的提问来源于stack exchange,提问作者Eischias
相关产品推荐
相关产品推荐

