Reputation: 23
i am trying to make flexible log10-grid in ggplot2. The idea is that between 0.1-1 the gridline breaks are 0.1 apart, between 1-10, they are 1 apart, between 10-100 they are 10 apart, etc
This way the grid lines repeat the same pattern as many times as required based on a variable vector (CAfails) with data i supply. This is what i came up with after a lot of tweaking:
CAfails<-data.frame(c(2.5,5.8,10.7,16.2,23,36.2,45.3,49.5,70.1,80.3,83.6,90))
LOG.as<-c(t((10^((floor(log10(min(CAfails)))-1):ceiling(log10(max(CAfails)))))%o%c(1:10)))
LOG.as<-LOG.as[-10*((floor(log10(min(CAfails))):ceiling(log10(max(CAfails))))+1)]
After which i pass it to ggplot2:
scale_x_log10(limits=c(1,10^(ceiling(log10(max(CAfails))))),breaks=LOG.as)
scale_y_log10(limits=c(0.1,10^(ceiling(log10(max(CAfails))))),breaks=LOG.as)
It works Ok but i was wondering if there wasn't a simpler and more easy way to do this
Here is a complete example:
CAfails<-data.frame(x=c(2.5,5.8,10.7,16.2,23,36.2,45.3,49.5,70.1,80.3,83.6,90))
LOG.as<-c(t((10^((floor(log10(min(CAfails)))-1):ceiling(log10(max(CAfails)))))%o%c(1:10)))
LOG.as<-LOG.as[-10*((floor(log10(min(CAfails))):ceiling(log10(max(CAfails))))+1)]
pdf$x <- 1:nrow(CAfails)
pdf$y <- CAfails$x
ggplot(data=pdf,aes(x,y)) + geom_point() +
scale_x_log10(limits=c(1,10^(ceiling(log10(max(CAfails))))),breaks=LOG.as) +
scale_y_log10(limits=c(0.1,10^(ceiling(log10(max(CAfails))))),breaks=LOG.as)
Upvotes: 2
Views: 204
Reputation: 22807
I think this works a bit better:
CAfails<-data.frame(x=c(2.5,5.8,10.7,16.2,23,36.2,45.3,49.5,70.1,80.3,83.6,90))
pdf$x <- 1:nrow(CAfails)
pdf$y <- CAfails$x
genbreaks <- function(x){
# only works on positive vals
minx <- min(x)
maxx <- max(x)
flminx <- floor(log10(minx))
clmaxx <- ceil(log10(maxx))
rv <- c()
xlo <- 10^flminx
for (i in flminx:clmaxx) {
rv <- c(rv,seq(xlo,xlo*10,xlo))
xlo <- xlo*10
}
return(rv)
}
ggplot(data=pdf,aes(x,y)) + geom_point(color="blue") +
scale_x_log10(breaks=genbreaks(pdf$x)) +
scale_y_log10(breaks=genbreaks(pdf$y))
Yielding:
But there could be a standard way of doing it.
Upvotes: 1