2013-07-23 58 views
2

我想繪製一個簡單的散點圖3組,覆蓋一段指示每個組的平均值和標記組。 我設法得到了帶有誤差線的散點圖,但我只想要一段指示平均值的段。我似乎也無法獲得集體標籤的權利。分類散點圖與平均段使用ggplot2在R

要得到摘要統計數據,我使用了從this page的函數「summarySE」。

有沒有更簡單的方法來做到這一點,並得到一個段而不是一個點的意思?

我真的很感謝你的幫忙!調用summarySE和創建dfc

dfc$tt <- factor(dfc$tt,labels=c("Group1", "Group2", "Group3")) 

當然:

library(ggplot2) 
library(plyr) 

df <- data.frame(tt = rep(1:3, each = 40), 
     val = round(rnorm(120, m = rep(c(4, 5, 7), each = 40)))) 

# After loading the summarySE function: 

dfc <- summarySE(df, measurevar="val", groupvars="tt") 


ggplot(dfc, aes(tt, val), main="Scatter plot with mean bars", 
     xlab="Groups", ylab="Values", names=c("Group1", "Group2", "Group3"))+ 
    geom_jitter(aes(tt, val), data = df, colour = I("red"), 
       position = position_jitter(width = 0.05)) + 
    geom_point(size = 3) + 
    geom_errorbar(aes(ymin=val-sd, ymax=val+sd), width = 0.01, size = 1) 
+0

+1!最好避免鏈接許多額外的函數,並添加一些數據樣本(df和dfc),不要忘記設置'set.seed'來讓您的示例具有完全可重現性。 – agstudy

+0

謝謝你的提示!我會知道下次 – user2337032

回答

2

您可以使用geom_crossbar()並使用valyyminymax值。使用scale_x_continuous()您可以更改原始數據的x軸標籤或使用@agstudy解決方案更改原始數據,並且標籤將自動出現。

ggplot()+ 
    geom_jitter(aes(tt, val), data = df, colour = I("red"), 
       position = position_jitter(width = 0.05)) + 
    geom_crossbar(data=dfc,aes(x=tt,ymin=val, ymax=val,y=val,group=tt), width = 0.5)+ 
    scale_x_continuous(breaks=c(1,2,3),labels=c("Group1", "Group2", "Group3")) 

enter image description here

+0

這是完美的!對於summarySE的代碼感到抱歉,它在這裏:http://www.cookbook-r.com/Graphs/Plotting_means_and_error_bars_(ggplot2)/ – user2337032

1

拿到小組標籤,您可以TT這樣的因素變化是連續的。

,並使用crossbar如下面的其他方案中提到,您可以:

enter image description here