在R中使用ggplot2在分类散点图中添加水平线 [英] Add horizontal lines in categorical scatter plot using ggplot2 in R

查看:1234
本文介绍了在R中使用ggplot2在分类散点图中添加水平线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制3个组的简单散点图,每个组具有不同的水平线(线段):例如,对于"a"组,在3处有一条折线;对于"b"组,在2.5处有一条折线,组6的hline.

I am trying to plot a simple scatter plot for 3 groups, with different horizontal lines (line segment) for each group: for instance a hline at 3 for group "a", a hline at 2.5 for group "b" and a hline at 6 for group "c".

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

非常感谢您的帮助!

推荐答案

当点足够时,切勿发送行:

Never send a line when a point can suffice:

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

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

There are other ways if this isn't acceptable, such as:

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

该点的缺点是厚度过大,无法控制宽度.

The downside for the point is the egregious thickness and no control over width.

该段的缺点是需要使用数字表示离散轴位置与系数.

The downside for the segment is the need to use numerics for the discrete axis position vs the factors.

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

I also should have set the random seed to ensure reproducibility.

这篇关于在R中使用ggplot2在分类散点图中添加水平线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆