Sequence x-Axis labels when when 'breaks' has already been defined (R, ggplot)

大憨熊 提交于 2021-02-05 09:28:37

问题


I used scale() function on my data to avoid high correlation when doing a mixed model. Now I want the original values to appear in my plot. So I reversed the scaling with x * attr(x, 'scaled:scale') + attr(x, 'scaled:center') and put the values in a new column of the dataframe that I use to plot. So as an example my data now looks something like this, where x is the real value and x.s the scaled value:

x <- sample(x=1:100, size = 50)
y <- sample(x=1:100, size = 50)
df <- as.data.frame(cbind(x,y))

df$x.s <- scale(df$x)

I want to plot this now with ggplot but show the values of x on x-axis and not the scaled values of x.s, so I did the following:

ggplot(df, aes(x = x.s, y = y))+
  geom_point()+
  scale_x_continuous(labels = df$x, breaks = df$x.s)+
  labs(x = "Canopy openness [%]", y = "Rarefied richness") + 
  theme_bw()

This works so far and the output looks something like this:

My problem now is, that i want the ticks on the x-Axis spread evenly which I would usually do with breaks=seq(0,100,10), but breaks is already defined to avoid error Error in f(..., self = self) : Breaks and labels are different lengths, now I can't figure out how to do this, any help would be appreciated!

If I use x on x-axis, in real Dataset my prediction regression with CI won´t fit anymore. Here are the Plots from my Dataset 1: with scaled values (x.s):

and 2: If I use x instead of x.s on x-axis


回答1:


There's a 1-to-1 linear mapping relationship between x and x.s, so one way you can go about this is to specify the desired labels in x's scale, and the corresponding breaks in x.s's scale:

ggplot(df, aes(x = x.s, y = y))+
  geom_point()+
  scale_x_continuous(labels = seq(0, 100, 10),
                     breaks = predict(lm(x.s ~ x, data = df),
                                      newdata = data.frame(x = seq(0, 100, 10)))) +
  labs(x = "Canopy openness [%]", y = "Rarefied richness") + 
  theme_bw()


来源:https://stackoverflow.com/questions/59052343/sequence-x-axis-labels-when-when-breaks-has-already-been-defined-r-ggplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!