Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use trans_new to shift a scale by a constant in ggplot2 without messing up the tick labels?

Tags:

r

scale

ggplot2

Let's say I have a continuous x-axis, and I want to add a constant value to each tickmark label. For example

ggplot(data=warpbreaks,aes(x=breaks,y=replicate)) + geom_point()

...will have tickmarks at 20, 40, and 60. What if I want those tickmarks to instead read 40, 60, and 80 without altering the rest of the plot? I tried this:

ggplot(data=warpbreaks,aes(x=breaks,y=replicate)) + geom_point() + 
scale_x_continuous(trans=trans_new("shift",function(x) x+20,identity))

That shifted the tickmarks by the appropriate amount but also deleted the leftmost one. If I use x+40 instead then two tickmarks get omitted from the left side leaving only one. If I do x+10 then all of them are shifted over by that amount and none of them are omitted. What's going on? How can I reliably shift the x values?

Motivation: when I fit regression models I usually center the numeric predictor variables (unless they actually encompass zero) to avoid absurd/misleading main effects estimates outside the support range of the data. However, when I plot the data and/or fitted values I want to return them to the original, non-centered scale.

like image 350
bokov Avatar asked Jan 10 '14 04:01

bokov


1 Answers

The first option is proposed by @mnel:

ggplot(data=warpbreaks,aes(x=breaks,y=wool)) + geom_point() + 
  scale_x_continuous(labels=function(x) x+20)

Note that you can change the data "locally" (inside a ggplot call), so here's another option:

ggplot(data=warpbreaks,aes(x=breaks+20,y=wool)) + geom_point()

In that case, no tinkering with scales is required.

like image 135
tonytonov Avatar answered Nov 15 '22 10:11

tonytonov