如何在ggplot中显示v''从0到56的全部x轴刻度(含无数据值)
问题说明
现有如下DataFrame:
v'' J'' theor_freq exp_freq delta 3 121 12540.05 12540.05 -0.0061 3 123 12514.11 12514.10 -0.0070 4 121 12453.72 12453.72 -0.0041 4 123 12427.90 12427.90 -0.0047 5 121 12368.11 12368.10 -0.0059 5 123 12342.41 12342.40 -0.0033
需要绘制delta随v''(0至56)变化的图形,要求每2个v''显示一个刻度。当前使用的ggplot代码如下:
p <- ggplot(data = df, aes(x = factor(`v''`), y = as.numeric(delta), colour = factor(`J''`))) + geom_point(size = 3) + geom_line() + geom_hline(yintercept = 0) + xlab("v''") + ylab("exp-theor")+ ggtitle("Before processing")+ labs(colour = "J''")+ scale_color_manual(values = c("121" = "black", "123" = "grey"))+ theme_bw()
目前图形仅显示有数据的v''值,尝试过scale_x_continuous、xlim、scale_x_discrete函数均未达到预期效果,需解决如何让x轴包含0到56的所有v''值(即使无对应数据点)并设置每2个v''显示一个刻度的问题。
解决方法
核心问题在于你把v''转成了因子(factor()),导致x轴被当作离散型变量处理,只会显示数据中存在的类别。要实现需求,需要把v''作为连续型变量处理,同时补充完整x轴的取值范围并设置刻度。
方法一:直接调整连续型x轴设置
无需补全空数据,ggplot会自动在无数据的位置断开线条,同时显示完整的x轴范围:
# 确保v''是数值型(如果原数据是字符/因子类型,先转换) df$`v''` <- as.numeric(df$`v''`) p <- ggplot(data = df, aes(x = `v''`, y = delta, colour = factor(`J''`))) + geom_point(size = 3) + geom_line() + geom_hline(yintercept = 0) + xlab("v''") + ylab("exp-theor") + ggtitle("Before processing") + labs(colour = "J''") + scale_color_manual(values = c("121" = "black", "123" = "grey")) + scale_x_continuous( limits = c(0, 56), # 固定x轴范围为0到56 breaks = seq(0, 56, by = 2), # 每2个v''显示一个刻度 expand = c(0, 0) # 可选:去掉轴两端的空白,让刻度从0对齐到56 ) + theme_bw() print(p)
方法二:补全完整数据集(可选)
如果希望x轴每个v''位置都被明确包含(即使无数据),可以先创建包含0到56所有v''值的完整数据集,再与原数据合并:
# 创建包含所有v''(0-56)和J''类别(121、123)的完整框架 full_df <- expand.grid(`v''` = 0:56, `J''` = c(121, 123)) # 合并原数据,无对应数据的delta会自动设为NA full_df <- merge(full_df, df, by = c("v''", "J''"), all.x = TRUE) # 使用完整数据集绘图 p <- ggplot(data = full_df, aes(x = `v''`, y = delta, colour = factor(`J''`))) + geom_point(size = 3, na.rm = TRUE) + # 跳过NA值的点 geom_line(na.rm = TRUE) + # 跳过NA值,线条在无数据处断开 geom_hline(yintercept = 0) + xlab("v''") + ylab("exp-theor") + ggtitle("Before processing") + labs(colour = "J''") + scale_color_manual(values = c("121" = "black", "123" = "grey")) + scale_x_continuous( limits = c(0, 56), breaks = seq(0, 56, by = 2) ) + theme_bw() print(p)
内容的提问来源于stack exchange,提问作者Ieva_Brakmane
相关产品推荐
相关产品推荐

