How to use trans_new to scale constant in ggplot2 without messing up label shortcuts?

Say I have a continuous X axis, and I want to add a constant value for each label label. for example

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

... will have marks at 20, 40, and 60. What if I want these marks to show 40, 60, and 80 instead, without changing 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))

This shifted the marks by the corresponding amount, but also deleted the leftmost one. If I use x+40instead, then two labels will be omitted on the left side, leaving only one. If I do x+10, then they are all shifted by this amount, and not one of them will be omitted. What's happening? How can I reliably shift x values?

Motivation: when I approach regression models, I usually center the predictor numeric variables (unless they actually include zero) to avoid absurd / misleading estimates of the main effects outside the data support range. However, when I draw data and / or set values, I want to return them to their original, off-center scale.

+4
source share
1 answer

The first option is offered 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 the ggplot call), so there is another option here:

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

In this case, mastering with scales is not required.

+3
source

All Articles