如何在ggplot中将辅助X轴设置在图表底部?
在图表底部添加双X轴的实现方案(R语言)
你需要在图表底部同时显示两个X轴,当前用ggplot2的sec_axis()默认将辅助轴放在顶部,以下提供两种实现方式:
首先是你的数据:
df <- read.table(text="Control Stress days sd_control sd_stress -0.2866667 -0.2833333 X1 0.11846237 0.05773503 -0.2566667 -1.0333333 X2 0.08144528 0.15275252 -0.4766667 -1.4500000 X3 0.09291573 0.10000000 -0.4900000 -1.2766667 X4 0.21517435 0.22501852 -0.4600000 -1.2666667 X5 0.07549834 0.40722639 -0.2633333 -1.0833333 X6 0.12662280 0.10408330 -0.2833333 -1.0333333 X7 0.03511885 0.07767453", header=T)
方法一:ggplot2实现底部双X轴
ggplot2原生的sec_axis()仅支持顶部辅助轴,需借助gtable调整布局:
- 绘制初始图表并预留底部空间:
library(ggplot2) library(gtable) library(grid) p <- ggplot(df, aes(x = Control, y = Stress)) + geom_point() + scale_x_continuous(sec.axis = sec_axis(~ . + 50, name = "辅助X轴")) + theme(plot.margin = unit(c(1, 1, 2, 1), "lines")) # 扩大底部边距,容纳辅助轴
- 提取gtable并调整辅助轴位置:
gt <- ggplotGrob(p) # 定位顶部辅助轴元素,将其移至主X轴下方 top_axis_idx <- which(grepl("axis", gt$layout$name) & !grepl("axis-b", gt$layout$name)) gt$layout$t[top_axis_idx] <- gt$layout$b[which(grepl("axis-b", gt$layout$name))] + 1 # 调整辅助轴标签的位置 top_label_idx <- which(grepl("xlab", gt$layout$name) & !grepl("xlab-b", gt$layout$name)) gt$layout$t[top_label_idx] <- gt$layout$b[top_axis_idx] + 1
- 绘制调整后的图表:
grid.draw(gt)
方法二:基础绘图(axis())实现
用基础绘图系统可以直接添加自定义底部辅助轴:
- 设置边距并绘制主图:
par(mar = c(8, 4, 2, 2)) # 增加底部边距,给辅助轴留位置 plot(df$Control, df$Stress, xlab = "主X轴", ylab = "Stress", pch = 16)
- 添加底部辅助轴:
# 获取主X轴的刻度,计算辅助轴对应值 main_ticks <- axTicks(1) aux_vals <- main_ticks + 50 # 在主轴下方绘制辅助轴,line参数控制垂直距离 axis(side = 1, at = main_ticks, labels = round(aux_vals, 2), line = 3, col = "red", col.axis = "red") mtext("辅助X轴", side = 1, line = 5, col = "red")
内容的提问来源于stack exchange,提问作者Juan Pablo Rincon
相关产品推荐
相关产品推荐

