1

黄土で平滑化された線をプロットしようとしていますが、既存の変数によって定義されているが平滑化されている陰影付きのエラー領域を含める方法を理解しようとしています。

このコードは、サンプル データを作成します。

set.seed(12345)
data <- cbind(rep("A", 100), rnorm(100, 0, 1))
data <- rbind(data, cbind(rep("B", 100), rnorm(100, 5, 1)))
data <- rbind(data, cbind(rep("C", 100), rnorm(100, 10, 1)))
data <- rbind(data, cbind(rep("D", 100), rnorm(100, 15, 1)))
data <- cbind(rep(1:100, 4), data)
data <- data.frame(data)
names(data) <- c("num", "category", "value")
data$num <- as.numeric(data$num)
data$value <- as.numeric(data$value)
data$upper <- data$value+0.20
data$lower <- data$value-0.30

以下のデータをプロットすると、次のようになります。

ggplot(data, aes(x=num, y=value, colour=category)) +
  stat_smooth(method="loess", se=F)

ここに画像の説明を入力

私が望むのは、次のようなプロットです。ただし、影付きの領域の上限と下限が、生成されたデータの「上限」変数と「下限」変数の平滑化された線で囲まれています。

ここに画像の説明を入力

どんな助けでも大歓迎です。

4

1 に答える 1

3

upperとの平滑化バージョンを追加する 1 つの方法を次に示しlowerます。と の LOESS 予測をデータ フレームに追加upperlower、 を使用してそれらをプロットしgeom_ribbonます。への呼び出し内でこれをすべて行うことができれば、より洗練されたものになりますggplot。これは、特殊な目的の関数を にフィードすることでおそらく可能でstat_summaryあり、他の誰かがそのアプローチを使用して回答を投稿することを願っています。

# Expand the scale of the upper and lower values so that the difference
# is visible in the plot
data$upper = data$value + 10
data$lower = data$value - 10

# Order data by category and num
data = data[order(data$category, data$num),]

# Create LOESS predictions for the values of upper and lower 
# and add them to the data frame. I'm sure there's a better way to do this,
# but my attempts with dplyr and tapply both failed, so I've resorted to the clunky 
# method below.
data$upperLoess = unlist(lapply(LETTERS[1:4], 
                  function(x) predict(loess(data$upper[data$category==x] ~ 
                                                  data$num[data$category==x]))))
data$lowerLoess = unlist(lapply(LETTERS[1:4], 
                  function(x) predict(loess(data$lower[data$category==x] ~ 
                                                  data$num[data$category==x]))))

# Use geom_ribbon to add a prediction band bounded by the LOESS predictions for 
# upper and lower
ggplot(data, aes(num, value, colour=category, fill=category)) +
  geom_smooth(method="loess", se=FALSE) +
  geom_ribbon(aes(x=num, y=value, ymax=upperLoess, ymin=lowerLoess), 
              alpha=0.2)

結果は次のとおりです。

ここに画像の説明を入力

于 2014-10-16T06:18:00.977 に答える