Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make gap between x and y axis and protruded ticks in ggplot2

Tags:

r

ggplot2

How can I create the following style of graph:

enter image description here

Notice the gap between x-y axis (red circle) and protruded ticks in x-y axis (arrow).

At best I can do is this now:

library(ggplot2)
p <- ggplot(mpg, aes(class, hwy)) +
     geom_boxplot() +
     theme_bw(base_size=10) 

p

enter image description here

like image 367
neversaint Avatar asked Jun 19 '17 01:06

neversaint


2 Answers

One option is to remove the built-in axis lines and then use geom_segment to add axes with a gap. In order to make it easier to get the broken axis lines in the right place, we also use scale_y_continuous to specify exactly where we want the axis breaks and limits. The code also shows how to increase the size of the tick marks.

ggplot(data=mpg, aes(class, hwy)) +
  geom_segment(y=10, yend=50, x=0.4, xend=0.4, lwd=0.5, colour="grey30", lineend="square") +
  geom_segment(y=5, yend=5, x=1, xend=length(unique(mpg$class)), 
               lwd=0.5, colour="grey30", lineend="square") +
  geom_boxplot() +
  scale_y_continuous(breaks=seq(10,50,10), limits=c(5,50), expand=c(0,0)) +
  theme_classic(base_size=12) +
  theme(axis.line = element_blank(),
        axis.ticks.length = unit(7,"pt")) 

enter image description here

like image 74
eipi10 Avatar answered Nov 15 '22 03:11

eipi10


You can achieve something similar using ggthemes which provides geom_rangeframe and theme_tufte.

library(ggplot2)
library(ggthemes)
ggplot(mpg, aes(class, hwy)) + 
  geom_boxplot() + 
  geom_rangeframe() + 
  theme_tufte() +
  theme(axis.ticks.length = unit(7, "pt"))

enter image description here More inspiration here.

like image 29
neilfws Avatar answered Nov 15 '22 02:11

neilfws