ggplot2 log scale of y axis causing curved lines

核能气质少年 提交于 2019-12-13 01:54:23

问题


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:


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")


来源:https://stackoverflow.com/questions/34256950/ggplot2-log-scale-of-y-axis-causing-curved-lines

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