[英]R lattice xyplot doesn't match grid to axes' ticks (not multiplot)
我正在嘗試通過以下代碼生成帶有點陣xyplot的圖:
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()
正如預期的那樣,它產生了一個漂亮的情節:
我希望繪圖上的網格與equispaced.log=F
生成的刻度線對齊。 xyplot的文檔僅討論了與多個圖有關的grid
,SO和其他站點中的一些其他線程也是如此(實際上,我從另一個站點獲得了grid=T
argumment: 在R中使用Lattice圖形 ,甚至在那里您也可以看到(當使用equispaced.log=F
時,網格與刻度“對齊”)。
以防萬一有人可能認為這是SO的重復:在網格圖形中將網格線對齊到軸上的線 ,請注意,這里的問題是如何在多圖中對齊網格(並且,當時,該線程還沒有答案)。
使用equispaced.log equispaced.log=F
如何使xyplot將網格線“對齊”到x刻度線? 謝謝!
看來您需要使用自定義面板功能來執行此操作,並使用panel.abline
代替panel.grid
。 我能想到的最好的方法是半手動設置刻度線。
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()
如果有幫助,這是一個ggplot解決方案。
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())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.