如何在ggplot2中使X轴所有刻度标记的间距相等?
问题描述
我绘制了一张带误差棒的散点折线图,X轴为hour(位置间隔小时数),但刻度4、12、24因数值间距较小显得拥挤。请问是否有方法让所有刻度标记的视觉间距相等,不受对应数值大小影响?
数据
# A tibble: 10 × 3 hour mean SE <dbl> <dbl> <dbl> 4 1.02 0.00568 8 0.83 0.00671 12 0.76 0.00831 24 0.68 0.0129 48 0.6 0.0116 72 0.56 0.0247 96 0.57 0.0259 120 0.6 0.0548 144 0.55 0.0429 168 0.42 0.0243
原始代码
library(ggplot2) ggplot(data3, aes(x = hour, y = mean)) + geom_errorbar(aes(ymin=mean-SE, ymax=mean+SE), width=.2) + geom_point() + geom_line()+ ylab("Mean speed (km/h)") + scale_x_continuous("Hours between locations", breaks = breaks) + theme_classic()
解决方案
要让所有X轴刻度视觉间距相等,核心是把hour转换为分类变量,这样ggplot会将每个刻度当作独立类别均匀排列,不再受数值大小影响。具体有两种实现方式:
方法1:直接将hour转为因子
修改数据中的hour列类型为因子,再用scale_x_discrete定义X轴:
library(ggplot2) # 将hour转为因子 data3$hour <- factor(data3$hour) ggplot(data3, aes(x = hour, y = mean)) + geom_errorbar(aes(ymin=mean-SE, ymax=mean+SE), width=.2) + geom_point() + geom_line(aes(group=1)) + # 必须添加group=1,否则折线无法连接所有点 ylab("Mean speed (km/h)") + xlab("Hours between locations") + theme_classic()
方法2:保留数值型hour,绘图时映射为因子
如果不想修改原始数据类型,可在绘图时直接将hour转为因子映射到X轴:
library(ggplot2) ggplot(data3, aes(x = factor(hour), y = mean)) + geom_errorbar(aes(ymin=mean-SE, ymax=mean+SE), width=.2) + geom_point() + geom_line(aes(group=1)) + ylab("Mean speed (km/h)") + xlab("Hours between locations") + theme_classic()
额外优化:自定义刻度标签(可选)
如果需要调整刻度显示样式,比如添加单位,可通过scale_x_discrete的labels参数实现:
ggplot(data3, aes(x = factor(hour), y = mean)) + geom_errorbar(aes(ymin=mean-SE, ymax=mean+SE), width=.2) + geom_point() + geom_line(aes(group=1)) + ylab("Mean speed (km/h)") + scale_x_discrete("Hours between locations", labels = paste(data3$hour, "h")) + # 给刻度添加"h"单位 theme_classic()
内容的提问来源于stack exchange,提问作者Cam
相关产品推荐
相关产品推荐

