RobinLovelace
RobinLovelace

Reputation: 4997

How to set scale_ defaults in ggplot theme?

I would like to create a theme that has tick marks different from the default, to avoid repeating + scale_x_continuous every time I create a custom plot.

Let's take a simple example, in which I want only tick marks at the limits:

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) )

This looks great (see below), but ideally I would be able to produce the same result without using scale_x_continuous as it's clunky. I want to replace theme_classic() with + mytheme and that should solve it.

Here's my best attempt so far at a solution:

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

Not sure if this is even possible, and happy to keep typing scale_x_continuous(...) every time. But it would be even better to change the defaults temporarily or, even better, in a custom theme.

Here's the plot axes I want to produce btw, and I want to produce many such plots (for plotting harmonographs):

custom x axis

Upvotes: 2

Views: 384

Answers (2)

Brian Diggs
Brian Diggs

Reputation: 58845

Turning @hadley's comment into an answer

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

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

(I also replaced function(x) x with the already existing function identity, but that is not a significant change.)

Upvotes: 3

tonytonov
tonytonov

Reputation: 25638

Not sure if that's what you want, but this will save you some space:

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)

Upvotes: 4

Related Questions