Capping axis lines

Stefan McKinnon Edwards sme@iysik.com

2017-04-27

Demonstration

A quick demonstration of capping the lines.

First, load the package, generate a dataset and display it.

#library(ggplot2)
library(splot)

dat1 <- data.frame(
  gp = factor(rep(letters[1:3], each = 10)),
  y = rnorm(30),
  cl = sample.int(3, 30, replace=TRUE),
  cl2 = sample(c('a','b','c'), 30, replace=TRUE)
)

my.theme <- theme_light()

(
  p <- ggplot(dat1, aes(gp, y)) + geom_point() + my.theme
)
Default ggplot2 plotting.

Default ggplot2 plotting.

NB: In order to manipulate the axis lines, they must be drawn. Modify the theme so the panel.border is not drawn (it will be on top of the axis lines), and have the axis lines drawn:

my.theme <- my.theme + theme(panel.border=element_blank(), axis.line = element_line())
p <- p + my.theme

Now, let’s have some fun.

We cap the bottom axis line to the right-most tick. The left end is also capped by the amount specified with the gap argument (at time of writing, defaulted at 0.01).

p + coord_capped_cart(bottom='right')
Using coord_capped_cart to cap the bottom axis from the right. The left axis is unaffected.

Using coord_capped_cart to cap the bottom axis from the right. The left axis is unaffected.

To keep the axis lines consistent, we also specify the left argument, which still caps the left axis line by the amount specified with the gap argument.

p + coord_capped_cart(bottom='right', left='none')
As before, but left axis is now also capped to give a consistent look.

As before, but left axis is now also capped to give a consistent look.

To avoid overplotting, we can apply a jitter. To emphasise that the x-axis is categorical, we can place brackets. We finally polish the plot by removing the redundant vertical grid lines.

ggplot(dat1, aes(gp, y)) + geom_point(position=position_jitter(width=0.2, height=0)) +
  coord_capped_cart(left='none', bottom=brackets_horisontal()) +
  my.theme + theme(panel.grid.major.x = element_blank())
Placing brackets brackets instead of ticks emphasises that the x-scale is categorical and not nominal.

Placing brackets brackets instead of ticks emphasises that the x-scale is categorical and not nominal.

The coord objects

Facets

# Facet grid -----------------
ggplot(dat1, aes(gp, y)) + geom_point() + 
  coord_capped_flip(bottom = 'left', left='none') + 
  theme(axis.title=element_blank(), plot.title=element_text(size=rel(1))) +
  facet_rep_grid(~cl)

dat2 <- rbind(dat1, data.frame(gp=letters[1:3], y=rnorm(3, 2), cl=3, cl2='b'))
ggplot(dat2, aes(gp, y)) + geom_point() + 
  coord_capped_flip(bottom = 'left', left='none') + 
  theme(axis.title=element_blank(), plot.title=element_text(size=rel(1))) +
  facet_rep_grid(.~cl, scales='free_y')

Also a quote using >:

“He who gives up [code] safety for [code] speed deserves neither.” (via)