Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving x or y axis together with tick labels to the middle of a single ggplot (no facets)

Tags:

plot

r

ggplot2

axes

I made the following plot in Excel:

enter image description here

But then I thought I would make it prettier by using ggplot. I got this far:

enter image description here

If you're curious, the data is based on my answer here, although it doesn't really matter. The plot is a standard ggplot2 construct with some prettification, and the thick line for the x-axis through the middle is achieved with p + geom_hline(aes(yintercept=0)) (p is the ggplot object).

I feel that the axis configuration in the Excel plot is better. It emphasizes the 0 line (important when the data is money) and finding intercepts is much easier since you don't have to follow lines from all the way at the bottom. This is also how people draw axes when plotting on paper or boards.

Can the axis be moved like this in ggplot as well? I want not just the line, but the tick labels as well moved. If yes, how? If no, is the reason technical or by design? If by design, why was the decision made?

like image 891
Superbest Avatar asked Aug 22 '16 03:08

Superbest


People also ask

How do you change the X axis tick label in R?

Option 1. Set xaxt = "n" and yaxt = "n" to remove the tick labels of the plot and add the new labels with the axis function. Note that the at argument sets where to show the tick marks.

How do you change the x and y axis in ggplot2?

Use scale_xx() functions It is also possible to use the functions scale_x_continuous() and scale_y_continuous() to change x and y axis limits, respectively.

How do you add X and Y labels in R plot?

To set labels for X and Y axes in R plot, call plot() function and along with the data to be plot, pass required string values for the X and Y axes labels to the “xlab” and “ylab” parameters respectively. By default X-axis label is set to “x”, and Y-axis label is set to “y”.


1 Answers

try this,

shift_axis <- 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())

}

p <- qplot(1:10, 1:10) + theme_bw() 
shift_axis(p, 5)

enter image description here

like image 142
baptiste Avatar answered Sep 28 '22 07:09

baptiste