简介
ggplot2 的默认x,y轴置于图片左边缘和下边缘,但有时候需要将原点(0,0)放置于图片正中,便于展示数据的象限信息。
另外,自己设置的x,y轴,由于坐标轴有geom_segment()和geom_text()函数构成,则坐标轴的标签文字可以根据geom_text函数进行个性化设置,可以根据颜色,字体,分组,大小等参数进行映射。
函数主体
函数主体来自center-x-and-y-axis-with-ggplot2,然后经过包装形成了draw_axis_line() 函数。
draw_axis_line <- function(length_x, length_y,
tick_step = NULL, lab_step = NULL){
axis_x_begin <- -1*length_x
axis_x_end <- length_x
axis_y_begin <- -1*length_y
axis_y_end <- length_y
if (missing(tick_step))
tick_step <- 1
if (is.null(lab_step))
lab_step <- 2
# axis ticks data
tick_x_frame <- data.frame(ticks = seq(axis_x_begin, axis_x_end,
by = tick_step))
tick_y_frame <- data.frame(ticks = seq(axis_y_begin, axis_y_end,
by = tick_step))
# axis labels data
lab_x_frame <- subset(data.frame(lab = seq(axis_x_begin, axis_x_end,
by = lab_step), zero = 0),
lab != 0)
lab_y_frame <- subset(data.frame(lab = seq(axis_y_begin, axis_y_end,
by = lab_step),zero = 0),
lab != 0)
# set tick length
tick_x_length = 15/length(tick_x_frame$ticks)/2
tick_y_length = 8/length(tick_y_frame$ticks)/2
# set zero point
data <- data.frame(x = 0, y = 0)
p <- ggplot(data = data) +
# draw axis line
geom_segment(y = 0, yend = 0,
x = axis_x_begin,
xend = axis_x_end,
size = 0.5) +
geom_segment(x = 0, xend = 0,
y = axis_y_begin,
yend = axis_y_end,
size = 0.5) +
# x ticks
geom_segment(data = tick_x_frame,
aes(x = ticks, xend = ticks,
y = 0, yend = 0 + tick_x_length)) +
# y ticks
geom_segment(data = tick_y_frame,
aes(x = 0, xend = 0 + tick_y_length,
y = ticks, yend = ticks)) +
# labels
geom_text(data=lab_x_frame, aes(x=lab, y=zero, label=lab), vjust = 1.5) +
geom_text(data=lab_y_frame, aes(x=zero, y=lab, label=lab), hjust= 1.5) +
theme_void()
return(p)
}
用法
- 将坐标轴设置到中心。
library(ggplot2)
p <- draw_axis_line(20, 4)
p + geom_point(aes(x =1, y =1))