使用ggplot在对数刻度上绘制小中断 [英] Plotting minor breaks on a log scale with ggplot

查看:48
本文介绍了使用ggplot在对数刻度上绘制小中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要获取 ggplot 以对数刻度正确绘制小中断,我必须执行以下操作:

To get ggplot to plot minor breaks correctly on a logarithmic scale, I had to do this thing:

faceplant1 <- function(x) {
    return (c(x[1]*10^.25, x[2]/10^.25))
}
faceplant2 <- function(x) {
    return (rep(seq(1,9),5)*rep(10^seq(-6,-2), each=9))
}
ggplot(mydata, aes(x=myseries)) +
    geom_density() +
    scale_x_log10(limits=c(1e-6, 1e-1),
                  breaks=10^seq(-6,-1),
                  minor_breaks=trans_breaks(faceplant1, faceplant2, n=45))

有没有更简单的方法来实现这一目标?

Is there a simpler way to achieve this?

最终结果应类似于:

推荐答案

这是我解决该问题的方法:

Here's my solution to that problem:

library(ggplot2)

log10_minor_break = function (...){
  function(x) {
    minx         = floor(min(log10(x), na.rm=T))-1;
    maxx         = ceiling(max(log10(x), na.rm=T))+1;
    n_major      = maxx-minx+1;
    major_breaks = seq(minx, maxx, by=1)
    minor_breaks = 
      rep(log10(seq(1, 9, by=1)), times = n_major)+
      rep(major_breaks, each = 9)
    return(10^(minor_breaks))
  }
}

mydata = data.frame(myseries = 10^(rnorm(1e4, mean=0, sd=0.5)))

myplot = 
  ggplot(mydata, aes(x=myseries))+
  geom_density()+
  scale_x_log10(minor_breaks=log10_minor_break())+
  theme(panel.grid.major.x = element_line(size=1.0),
        panel.grid.minor.x = element_line(size=2))

myplot

它与您已经完成的操作非常相似,但通常适用.还有一个小改进:在您的示例中,它会将小中断扩展到1e-6以下和1e-1以上.

It is very similar to what you've already done but applies generally. And a minor improvement: it would expand the minor breaks below 1e-6 and above1e-1 in your example.

我从查看功能 trans_break 开始,并将其简化为最基本的元素.

I have started from looking at the function trans_break and reduced it to its most fundamental element.

同样值得考虑的是注解_logticks()函数:

It is also worth considering the annotation_logticks() function:

myplot+annotation_logticks(side="b")

这篇关于使用ggplot在对数刻度上绘制小中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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