【问题标题】:Add horizontal lines in categorical scatter plot using ggplot2 in R使用 R 中的 ggplot2 在分类散点图中添加水平线
【发布时间】:2017-01-28 19:22:24
【问题描述】:

我正在尝试为 3 个组绘制一个简单的散点图,每个组具有不同的水平线(线段):例如组“a”的 3 处的 hline,组“b”的 2.5 处的 hline 和组“c”在 6 处的一条线。

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))

非常感谢您的帮助!

【问题讨论】:

  • 试过这样的事情:geom_segment(aes(x=0.75,xend=1.25,y=3,yend=3))

标签: r ggplot2 line categorical-data scatter


【解决方案1】:

谢谢它工作正常。但是,当我使用气泡图时,第二种解决方案不起作用。

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))

eval(expr, envir, enclos) 中的错误:找不到对象's'

【讨论】:

    【解决方案2】:

    当一个点足够时,永远不要发送一条线:

    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))
    

    如果不能接受,还有其他方法,比如:

    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))
    

    该点的缺点是厚度过大且无法控制宽度。

    该段的缺点是需要使用数字来表示离散轴位置与因子。

    我还应该设置随机种子以确保可重复性。

    【讨论】:

      猜你喜欢
      • 2019-05-15
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多