11

これがプロットのコードです

library(ggplot2)
df <- data.frame(gp = factor(rep(letters[1:3], each = 10)), y = rnorm(30))
library(plyr)
ds <- ddply(df, .(gp), summarise, mean = mean(y), sd = sd(y))
ggplot(df, aes(x = gp, y = y)) +
   geom_point() +
   geom_point(data = ds, aes(y = mean), colour = 'red', size = 3)

ここに画像の説明を入力してください

このプロットの凡例を使用して、データ値と平均値を次のように識別します。

Black point = Data
Red point   = Mean.

どうすればこれを達成できますか?

4

2 に答える 2

17

手動スケールを使用します。つまり、あなたの場合scale_colour_manualです。aes()次に、各geomの関数を使用して、色をスケールの値にマップします。

ggplot(df, aes(x = gp, y = y)) +
  geom_point(aes(colour="data")) +
  geom_point(data = ds, aes(y = mean, colour = "mean"), size = 3) +
  scale_colour_manual("Legend", values=c("mean"="red", "data"="black"))

ここに画像の説明を入力してください

于 2012-08-07T04:53:32.830 に答える
7

同じdata.frame内の平均変数とデータを組み合わせて、列ごとに色/サイズを組み合わせることができます。これは、dataまたはmean

library(reshape2)

# in long format
dsl <- melt(ds, value.name = 'y')
# add variable column to df data.frame
df[['variable']] <- 'data'
# combine
all_data <- rbind(df,dsl)

# drop  sd rows

data_w_mean <- subset(all_data,variable != 'sd',drop = T)

# create vectors for use with scale_..._manual
colour_scales <- setNames(c('black','red'),c('data','mean'))
size_scales <- setNames(c(1,3),c('data','mean') )

ggplot(data_w_mean, aes(x = gp, y = y)) +
  geom_point(aes(colour = variable, size = variable)) +
  scale_colour_manual(name = 'Type', values = colour_scales) +
  scale_size_manual(name = 'Type', values = size_scales)

ここに画像の説明を入力してください

または、組み合わせることができませんでしたが、両方のデータセットに列を含めました

dsl_mean <- subset(dsl,variable != 'sd',drop = T)  
ggplot(df, aes(x = gp, y = y, colour = variable, size = variable)) +
  geom_point() +
  geom_point(data = dsl_mean) +
  scale_colour_manual(name = 'Type', values = colour_scales) +
  scale_size_manual(name = 'Type', values = size_scales)

同じ結果が得られます

于 2012-08-07T04:53:20.013 に答える