I am attempting to adjust the position of the tick marks on my plot so they fall along the axis instead of on the perimeter of the plot (which is the default). I have tried using the axis.ticks argument within ggplot2 and this did not work. Here are some example data and the code necessary to produce the graph I am working with:
library(ggplot2)
dat <- data.frame(v1 = c(1, 3, -2, 2, 1, 4, -2, 2),
v2 = c(-1, 2, 1, -3, 4, 1, -1, 2))
p = ggplot()
p + geom_point(aes(dat$v1, dat$v2) ,shape = 21, size = 3) +
geom_vline(xintercept = 0, linetype = "dashed") +
geom_hline(yintercept = 0, linetype = "dashed") +
theme_bw()
Please advise on any packages, functions, or arguments that can be used to move the tick marks onto the axises instead of the outside edges of the graphing area.
Bringing together @user20650's comment linking to Moving x or y axis together with tick labels to the middle of a single ggplot (no facets), which shares @baptiste and @user73708's functions. I removed your dashed lines, and moved the data and aes to the ggplot call.
library(ggplot2)
dat <- data.frame(v1 = c(1, 3, -2, 2, 1, 4, -2, 2),
v2 = c(-1, 2, 1, -3, 4, 1, -1, 2))
shift_axis_y <- function(p, y=0){
g <- ggplotGrob(p)
dummy <- data.frame(y=y)
ax <- g[["grobs"]][g$layout$name == "axis-b"][[1]]
p + annotation_custom(grid::grobTree(ax, vp = grid::viewport(y=1, height=sum(ax$height))),
ymax=y, ymin=y) +
geom_hline(aes(yintercept=y), data = dummy) +
theme(axis.text.x = element_blank(),
axis.ticks.x=element_blank())
}
shift_axis_x <- function(p, x=0){
g <- ggplotGrob(p)
dummy <- data.frame(x=x)
ax <- g[["grobs"]][g$layout$name == "axis-l"][[1]]
p + annotation_custom(grid::grobTree(ax, vp = grid::viewport(x=1, width = sum(ax$height))),
xmax=x, xmin=x) +
geom_vline(aes(xintercept=x), data = dummy) +
theme(axis.text.y = element_blank(),
axis.ticks.y=element_blank())
}
p <- ggplot(dat, aes(v1, v2)) +
geom_point(shape = 21, size = 3) +
theme_bw()
p<-shift_axis_y(p, y=0)
p<-shift_axis_x(p, x=0)
p
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With