ggplot2 log scale of y axis causing curved lines

2019-08-08 15:00发布

I’d like to graph some data as means of groups over time, with lines connecting the different mean time points for each group.

The code for this is:

line<-ggplot(dat, aes(Time, Cortisol.ngmL, shape=T))

line+
stat_summary(fun.y=mean, geom="point", size=4, aes(group=T))+
stat_summary(fun.y=mean, geom="line", aes(group=T), linetype="dashed", lwd=0.7)

But…I want the y axis logged (log10). And when I do this the lines connecting the groups across time become curved (code below)

line<-ggplot(dat, aes(Time, Cortisol.ngmL, shape=T))

line+
stat_summary(fun.y=mean, geom="point", size=4, aes(group=T))+
stat_summary(fun.y=mean, geom="line", aes(group=T), linetype="dashed", lwd=0.7)+
coord_trans(y="log10")

Does anyone know a way I can have a log scale and straight lines?

1条回答
霸刀☆藐视天下
2楼-- · 2019-08-08 15:27

I use this function to connect points with straight lines in log scale:

log_line <- function(x, y, n = 1000) {
  l <- lapply(2:length(x),
              function(i, n) {
                xl <- seq(x[i - 1], x[i], (x[i] - x[i - 1]) / n)
                yl <- exp(log(y[i]) + (xl - x[i]) * (log(y[i]) - log(y[i - 1])) / (x[i] - x[i - 1]))
                return(data.frame(x = xl, y = yl))
              },
              n)

  return(do.call(rbind, l))
}

The arguments are the x and y coordinates of the points you want to connect with a straight line in log scale and the n number of points you want to predict between each pair of original points.

This function fits a straight line in log scale between each points, predicts n new points between the two original points and than converts them back to the original scale. The output is a data frame with the predicted values x and y coordinates.

It can be easily added to a ggplot:

v1 <- 1:10
v2 <- exp(-v1)

ggplot() +
  geom_point(aes(v1, v2)) +
  geom_line(aes(x, y), data = log_line(v1, v2)) +
  coord_trans(y = "log")
查看更多
登录 后发表回答