2016-09-20 148 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):对象的'未找到