Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 Tufte lines same as axis ticks

Tags:

r

ggplot2

tufte

I used Tufte lines with ggplot2 for years now, but I've always wondered if there was an automated way to draw them, so they correspond to axis tics.

The usual way I draw them is like this :

ggplot(mtcars, aes(x=mpg, y=cyl))+
geom_bar(stat = "identity")+
theme_tufte()+
geom_hline(yintercept = c(5,10,15), col="white", lwd=3)

Tufte lines

Here I specify the ticks with yintercept = c(5,10,15), but recently I was building a Shiny app with changing axes, so I can't specify fixed ticks.

Is there a way for me to say something like yintercept = tickmarks, so that my Shiny app will always work without precalculating and defining both the axis and the Tufte lines manually?

like image 226
magasr Avatar asked May 07 '17 16:05

magasr


1 Answers

You can use ggplot_build to extract the tickmark positions as a vector and then pass that to the yintercept argument of geom_hline:

p <- ggplot(mtcars, aes(x=mpg, y=cyl))+
    geom_bar(stat = "identity")+
    theme_tufte()

tickmarks <- ggplot_build(p)$layout$panel_ranges[[1]]$y.major_source  

p + geom_hline(yintercept = tickmarks, col="white", lwd=3)
like image 140
Sraffa Avatar answered Oct 20 '22 18:10

Sraffa