2016-09-20 97 views
1

我想繪製3組的簡單散點圖,每組有不同的水平線(線段):例如,對於組「a」 ,對於組「b」爲2.5,對於組「c」爲6。使用ggplot2在R中添加分類散點圖中的水平線

library(ggplot2) 
df <- data.frame(tt = rep(c("a","b","c"),40), 
      val = round(rnorm(120, m = rep(c(4, 5, 7), each = 40)))) 
ggplot(df, aes(tt, val))+ 
geom_jitter(aes(tt, val), data = df, colour = I("red"), 
position = position_jitter(width = 0.05)) 

我真的很感謝您的幫忙!

+0

嘗試是這樣的:'geom_segment(AES(X = 0.75,xend的= 1.25,Y = 3,YEND = 3))' –

回答

0

從不發送線時的一個點可以是足夠的:

library(ggplot2) 

df <- data.frame(tt = rep(c("a","b","c"),40), 
       val = round(rnorm(120, m = rep(c(4, 5, 7), each = 40)))) 

hline <- data.frame(tt=c("a", "b", "c"), v=c(3, 2.5, 6)) 

ggplot(df, aes(tt, val))+ 
    geom_point(data=hline, aes(tt, v), shape=95, size=20) + 
    geom_jitter(aes(tt, val), data = df, colour = I("red"), 
       position = position_jitter(width = 0.05)) 

enter image description here

還有其他的方法,如果這是不能接受的,如:

hline <- data.frame(tt=c(1, 2, 3), v=c(3, 2.5, 6)) 

ggplot(df, aes(tt, val))+ 
    geom_jitter(aes(tt, val), data = df, colour = I("red"), 
       position = position_jitter(width = 0.05)) + 
    geom_segment(data=hline, aes(x=tt-0.25, xend=tt+0.25, y=v, yend=v)) 

enter image description here

該點的缺點是厚度過大,無法控制寬度。

該部分的缺點是需要使用離散軸位置與因子的數值。

我也應該設置隨機種子以確保可重複性。

0

感謝它工作正常。但是,當我使用氣泡圖時,第二種解決方案不起作用。在EVAL

df <- data.frame(tt = rep(c("a","b","c"),40), 
val = round(rnorm(120, m = rep(c(4, 5, 7), each = 40))),s=rep(c(1,10,5,50),each=30)) 

hline <- data.frame(tt=c(1, 2, 3), v=c(3, 2.5, 6)) 

ggplot(df, aes(tt, val,size=s))+ 

geom_jitter(aes(tt, val), data = df, colour = I("red"), 
position = position_jitter(width = 0.05))+ 
geom_segment(data=hline, aes(x=tt-0.25, xend=tt+0.25, y=v, yend=v)) 

錯誤(表達式,ENVIR,enclos):對象的'未找到

相關問題