r-geom_smooth()曲线未显示在绘图上

时间:2018-12-08 02:13:11

标签: r ggplot2 linear-regression

为什么以下代码生成的绘图中没有显示geom_smooth线?

test <- function() {
  require(ggplot2)
  # browser()
  set.seed(1);

  df <- data.frame(matrix(NA_real_, nrow = 50, ncol = 2))
  colnames(df) <- c("xdata", "ydata")

  df$xdata = as.numeric(sample(1:100, size = nrow(df), replace = FALSE))
  df$ydata = as.numeric(sample(1:3, size = nrow(df), prob=c(.60, .25, .15), replace = TRUE))

  plot1 <- ggplot(df, aes(x = reorder(xdata,-ydata), y = ydata)) + 
    geom_point(color="black") + 
    geom_smooth(method = "loess") + 
    theme(legend.position = "none", axis.text.x = element_blank(), axis.ticks.x = element_blank() )
  plot1
}
test()

我的x和y数据绝对是数字的,如以下问题所述:geom_smooth in ggplot2 not working/showing up

图:

enter image description here

1 个答案:

答案 0 :(得分:2)

xdataydata可能是数字,但是geom_smooth似乎并不能识别您的reorder函数输出。如果将as.numeric包装在重排零件周围,则该行会返回:

ggplot(df, aes(x = as.numeric(reorder(xdata,-ydata)), y = ydata)) + 
  geom_point(color="black") + 
  geom_smooth(method = "loess") + 
  theme(legend.position = "none", axis.text.x = element_blank(), 
        axis.ticks.x = element_blank())

reorder wrapped in as numeric