简体   繁体   中英

How to change the x-axis scale in sjPlot package?

I am working with the sjPlot package. I am plotting the predicted values of a linear model similar to the following example:

#R Version: 3.6.2
set.seed(1993)

x <- seq(1980, 2018, 2)
y <- runif(length(x), 1,100)

df <- data.frame(x,y)

library(ggplot2)
library(sjPlot)

Results <- lm(y ~ as.factor(x), data = df); summary(Results)

plot_model(Results, type = "pred", terms = c("x"))

I want to rescale the x-axis so that instead of it proceeding by every two years, i want it to proceed by every 4 years.

However, when I try to rescale the x axis using scale_x_continuous or scale_x_discrete it doesn't work, even though it is the correct code in ggplot2

#This works in ggplot:
ggplot(df, aes(x= x, y=y))+
  geom_point() +
  scale_x_continuous("Cycle", labels = seq(1980, 2018, 4), breaks = seq(1980, 2018, 4))

#But it doesn't work in sjPlot package -- as either scale_x_continuous
plot_model(Results, type = "pred", terms = c("x")) +
  scale_x_continuous("Cycle", labels = seq(1980, 2018, 4), breaks = seq(1980, 2018, 4))
  
#or  either scale_x_discrete
plot_model(Results, type = "pred", terms = c("x")) +
  scale_x_discrete("Cycle", labels = seq(1980, 2018, 4), breaks = seq(1980, 2018, 4)

How can I rescale the x-axis to proceed by 4, instead of 2?

Update

  1. The only message that pops up after I run the plot code is as follows: Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale. Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.

  2. Here is my output for plot_model code. It is the same whether I use scale_x_continuous or scale_x_discrete .

在此处输入图像描述

Just wanted to add to @chemdork123 's answer that your code works fine for me as well.

#R Version: 3.6.2
set.seed(1993)

x <- seq(1980, 2018, 2)
y <- runif(length(x), 1,100)

df <- data.frame(x,y)

library(ggplot2)
library(sjPlot)

Results <- lm(y ~ as.factor(x), data = df); summary(Results)

plot_model(Results, type = "pred", terms = c("x"), show.data = TRUE) + 
  scale_x_continuous("Cycle", labels = seq(1980, 2018, 4), breaks = seq(1980, 2018, 4))
ggsave('sjplot_replicate.jpeg')

which gives me this plot:

在此处输入图像描述

So it seems like it's all good!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM