错误:R中的“美学必须是长度一个或相同的长度”

时间:2017-04-27 13:43:58

标签: r ggplot2

我尝试在R中运行以下函数:

GainChart <- function(score, good.label, n.breaks = 50, ...){

  df <- data.frame(percentiles = seq(0, 1, length = n.breaks),
                   gain = Gain(score, good.label, seq(0, 1, length = n.breaks)))

  p <-  ggplot(df, aes(percentiles, gain))  + geom_line(size = 1.2, colour = "darkred")
  p <- p + geom_line(aes(x = c(0,1), y = c(0,1)), colour = "gray", size = 0.7)
  p <- p + scale_x_continuous("Sample Percentiles", labels = percent_format(), limits = c(0, 1))
  p <- p + scale_y_continuous("Cumulative Percents of Bads", labels = percent_format(), limits = c(0, 1))
  p
}

我收到以下错误消息:“错误:美学必须是长度1或与数据相同(50):x,y”

调用该函数的命令是:

GainChart(data_sampni$score,data_sampni$TOPUP_60d)

2 个答案:

答案 0 :(得分:0)

你的第二个geom_line()没有意义。看来你试图在[0,0]和[1,1]之间划一条线。在这种情况下,请使用geom_abline()

+ geom_abline(aes(intercept = 0, slope = 1))

答案 1 :(得分:0)

geom_line的帮助表示如果data=NULL(默认值),那么数据将从父图继承。这就是你不匹配的地方。

你把第二行更改为:

p <- p + geom_line(aes(x,y), data=data.frame(x=c(0,1), y=c(0,1)))

然后它应该工作。