【问题标题】:How to set scale_ defaults in ggplot theme?如何在 ggplot 主题中设置 scale_ 默认值?
【发布时间】:2013-12-30 21:11:45
【问题描述】:

我想创建一个带有不同于默认刻度标记的主题,以避免每次创建自定义绘图时重复+ scale_x_continuous

让我们举一个简单的例子,我只想在极限处打勾:

A = 1; f = 5; p = 0; d = 0.4
t = seq(from = 0, to = 10, by = 0.01)

x = A * sin(t * f + p) * exp(-d * t)
numticks = 1

qplot(x = t, y = x) + theme_classic() + 
  scale_x_continuous(breaks = scales::trans_breaks("identity", function(x) x, n=numticks) )

这看起来很棒(见下文),但理想情况下我可以在不使用 scale_x_continuous 的情况下产生相同的结果,因为它很笨重。我想用+ mytheme 替换theme_classic() 应该可以解决它。

这是我迄今为止在解决方案方面的最佳尝试:

mytheme <- theme_classic() + 
theme(scale_x_continuous(breaks=trans_breaks("identity", function(x) x, n=numticks)) 

不确定这是否可能,并且很高兴每次都输入scale_x_continuous(...)。但最好暂时更改默认设置,或者在自定义主题中更改。

这是我想生成的绘图轴,我想生成许多这样的图(用于绘制harmonographs):

【问题讨论】:

  • Ps 考虑这个的出发点可能是 ggplot2 docs。在这里看不到答案docs.ggplot2.org/0.9.3/scale_continuous.html
  • 将列表添加到绘图会添加列表的每个元素,因此您的主题函数可以返回包含实际主题和比例的列表。

标签: r ggplot2 themes scale


【解决方案1】:

将@hadley 的评论变成答案

mytheme <- list(theme_classic(),
                scale_x_continuous(breaks=trans_breaks("identity", 
                                                       identity, 
                                                       n=numticks)))

qplot(x = t, y = x) + mytheme

(我也用已经存在的函数identity替换了function(x) x,但这并不是一个重大的变化。)

【讨论】:

    【解决方案2】:

    不确定这是否是您想要的,但这会为您节省一些空间:

    custom_ticks <- function(n) {
      scale_x_continuous(breaks = 
        scales::trans_breaks("identity", function(x) x, n=n))
    }
    
    p <- qplot(x = t, y = x) + theme_classic() 
    p + custom_ticks(2)
    p + custom_ticks(10)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多