使用"ggplot2"绘制的对数网格 [英] Logarithmic grid for plot with 'ggplot2'

查看:211
本文介绍了使用"ggplot2"绘制的对数网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试使用ggplot2用对数间隔的网格创建图,如下图所示.我得到等距的网格,但没有对数的网格.我知道我缺少一些参数,到目前为止我似乎还没有得到.我已经看到很多关于该主题的问题,例如使用ggplot2(动态而非手动)将对数转换为正常刻度很漂亮,但不能解决我正在寻找的问题.

I am trying to create a plot with logarithmically spaced grids using ggplot2 just like in the below figure. I get equidistant grids, but not log spaced ones. I know I am missing some parameter which I don't seem to get as of now. I have seen a lot of questions on the topic like Pretty ticks for log normal scale using ggplot2 (dynamic not manual), but do not solve the problem I am looking for.

set.seed(5)
x <- rlnorm(1000, meanlog=3.5, sdlog=1)
y <- rlnorm(1000, meanlog=4.0, sdlog=1)
d <- data.frame(x, y)

plot(x, y, log="xy", las=1)
grid(nx=NULL, ny=NULL, col= "blue", lty="dotted", equilogs=FALSE)
library(magicaxis)
magaxis(side=1:2, ratio=0.5, unlog=FALSE, labels=FALSE)

library(ggplot2)
library(MASS)
library(scales)
a <- ggplot(d, aes(x=x, y=y)) + geom_point() +
     scale_x_log10(limits = c(1, NA), 
                   labels = trans_format("log10", math_format(10^.x)),
                   breaks=trans_breaks("log10", function(x) 10^x, n=4)) +
     scale_y_log10(limits = c(1, NA),
                   labels = trans_format("log10", math_format(10^.x)),
                   breaks=trans_breaks("log10", function(x) 10^x, n=4)) +
     theme_bw() + theme(panel.grid.minor = element_line(color="blue", linetype="dotted"), panel.grid.major = element_line(color="blue", linetype="dotted"))
a + annotation_logticks(base = 10)

推荐答案

要基于Gabor的答案,不必仅在图的确切范围内定义刻度.相反,您可以为大范围的值定义中断,该中断将涵盖您希望看到的几乎所有内容,并使用这些值为任何图创建漂亮的网格线.尽管这也许不是最优雅的解决方案,但它比每次必须手动找出范围都更简单,更通用.

To build on Gabor's answer, it is unnecessary to define the ticks only in the exact range of the plot. You can instead define breaks for a large range of values that will cover pretty much everything you'd ever expect to see and use those to create nice grid lines for any plot. While perhaps not the most elegant solution, it's easy and more generalizable than having to manually figure out ranges every time.

breaks <- 10^(-10:10)
minor_breaks <- rep(1:9, 21)*(10^rep(-10:10, each=9))

d %>% 
    ggplot(aes(x, y)) +
        geom_point() +
        scale_x_log10(breaks = breaks, minor_breaks = minor_breaks) +
        scale_y_log10(breaks = breaks, minor_breaks = minor_breaks) +
        annotation_logticks() +
        coord_equal() +
        theme_bw()

这篇关于使用"ggplot2"绘制的对数网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆