更新时间:2023-11-26 23:45:22
Maybe there is a straight solution but this is a hack/workaround that I can think of using geom_segment
:
p <- ggplot(mtcars, aes(cyl, mpg)) +
geom_point()
#get the ylim and xlim
xmin <- min(ggplot_build(p)$layout$panel_ranges[[1]]$x.range)
xmax <- max(ggplot_build(p)$layout$panel_ranges[[1]]$x.range)
ymin <- min(ggplot_build(p)$layout$panel_ranges[[1]]$y.range)
ymax <- max(ggplot_build(p)$layout$panel_ranges[[1]]$y.range)
# Create a simple secondary axis
p + scale_y_continuous(sec.axis = sec_axis(~.+10)) +
theme(axis.text.y.right = element_text(color = "red"))+
geom_segment(aes(x=xmax+0.2,xend=xmax+0.2,
y=ymin-2,yend=ymax+2), color = "red") +
coord_cartesian(xlim=c(xmin, xmax), ylim=c(ymin, ymax))