Xyplot R-lattice does not match tick grid (not multipliers)

I am trying to create a graph with xyplot lattice with the following code:

set.seed(123) #### make it reproducible df<-data.frame(x=runif(100,1,1e7),y=runif(100,0.01,.08),t=as.factor(sample(1:3,100,replace=T))) png("xyplot_grid_misaligned.png",800,800) p<-xyplot(y ~ x,groups=t,data=df,scales=list(x=list(log=10,equispaced.log=F)),auto.key=T,ylim=c(-.01,.1),grid=T) print(p) dev.off() 

It produces, as expected, a beautiful plot: xyplot with grid misaligned

I want the grid on the chart to be aligned with the marks generated by equispaced.log=F The xyplot documentation only discusses grid with respect to several graphs, as well as some other flows in SO and other sites (in fact, I got the argument grid=T from another site: Using the graphic grid in R , and even there you can see that when using equispaced.log=F grid "shifts" with ticks).

Just in case, someone might think that this is a duplicate of SO: aligning-grid-lines-to-axis-ticks-in-lattice-graphics , please note that the question is how to align the grids in the multiset (and even time thread has not yet answered).

How can I use xyplot "align" grid lines to x ticks when using equispaced.log=F ? Thanks!

+5
source share
2 answers

It seems you need to use the custom panel function for this and use panel.abline instead of panel.grid . The best I could think of was to check the boxes manually.

 library(lattice) set.seed(123) #### make it reproducible df<-data.frame(x=runif(100,1,1e7),y=runif(100,0.01,.08),t=as.factor(sample(1:3,100,replace=T))) # do this one by hand, since you had "equispaced.log=F" x.at = c(5e3, 10e3, 5e4, 10e4, 5e5, 10e5, 5e6, 10e6) # but this one is done with `pretty` as usual y.at = pretty(df$y,4) png("xyplot_grid_aligned.png",600,600) p <- xyplot(y ~ x,groups=t,data=df, scales=list(x=list(at=x.at,log=10), y=list(at=y.at)), auto.key=T, ylim=c(-.01,.1), panel = function(...) { panel.abline(v=log10(x.at),h=y.at,col="lightgrey") panel.xyplot(...) } ) print(p) dev.off() 

enter image description here

+3
source

Here is the ggplot solution if it is useful.

 ggplot(df, aes(x=x, y=y, color=t)) + geom_point(shape=21) + scale_x_log10(breaks=c(5e3, 1e4, 5e4,1e5,5e5,1e6,5e6,1e7)) + theme_bw() + theme(panel.grid.minor=element_blank()) 

enter image description here

+2
source

Source: https://habr.com/ru/post/1206571/


All Articles