R and ggplot2: How to turn axes into logarithmic scale? Given confidence interval constraints

867 Views Asked by At

I'm new here and would really appreciate some help! I've got a simple r script to plot log transformed data using ggplot and also plot on the 95% confidence and prediction intervals. However, I'm stuck on how to format the axes... I'd like them to be in log scale. I learned this from a tutorial and have tried to go through the script then transform the axes, but it messes up the confidence intervals.

I've tried using:

scale_y_continuous(trans=log2_trans())+
scale_x_continuous(trans=log2_trans())

but that doesn't transform the 95% confidence interval... Any suggestions would be appreciated! Basically, I'm just looking for an easy way to get log scales that look nice on the already nice graph.

Here's my code (I didn't include all the data just a bit for reference):

x <- c(6135.0613509,945.2650501,1927.8260200,110.0000000,
    3812.9674276,3.2991626,1173.4923354,945.2650501,
    114.2114798,11.2463797)
y <- c(370.00,32.00,2900.00,52.00,1500.00,0.06,16.00,50.00,5.00,11.00)
df <- data.frame(x, y)

# Log transformation
log_x <- log(x)
log_y <- log(y)

# Plot
plot(log_x,log_y)

# Linear Regression - linear model function
model1 <- lm(log_y ~ log_x, data = df)
summary(model1)
abline(model1, col = "lightblue") # Add trendline to plot of log transformed 
data

# load ggplot2
library(ggplot2)

# Confidence and Prediction intervals
temp_var <- predict(model1, interval = "prediction")
## Warning in predict.lm(model1, interval = "prediction"): predictions on 
## current data refer to _future_ responses

new_df <- cbind(df, temp_var)

ggplot(new_df, aes(log_x, log_y))+
  geom_point() +
  geom_line(aes(y = lwr), color = "red", linetype = "dashed")+
  geom_line(aes(y = upr), color = "red", linetype = "dashed")+
  geom_smooth(method = lm, se = TRUE)
0

There are 0 best solutions below