r - 用r的ggplot2中的线连接点

标签 r ggplot2 line scatter-plot segment

这是我的数据:

    mydata <- data.frame (grp = c(  1,   1,   1,  1, 1,  1, 1, 1, 1, 
     2,2, 2, 2,2, 2, 2, 2, 2),
    grp1 = c("A", "A", "A", "A", "A",  "B", "B", "B", "B" ,  
    "A", "A", "A", "A",      "B", "B", "B", "B", "B"), 
   namef = c("M1", "M3", "M2", "M4", "M5","M1", "M3", "M4", 
    "M0", "M6", "M7", "M8",       "M10", "M6", "M7", "M8", "M9", "M10"),
     dgp = c(1, 1, 1, 1, 1,  1.15, 1.15,1.15, 1.15 ,
        2, 2, 2, 2,2.15, 2.15, 2.15, 2.15, 2.15), 
    position = c(1.1, 2.1, 3.2, 4.1, 5.0,
     1.1, 2.0, 5.0, 6.2, 1.0,3.0, 4.1, 5.0,  
    1.0, 2.1, 3.01, 4.0, 5.02))

require(ggplot2)

plt <- ggplot(mydata) +   geom_point(aes(position, dgp, 
group = factor(dgp)),   size = 2, colour = "purple") +
geom_text(data = mydata,aes(x=position,y=dgp + 0.05,
 label=namef))


t

我想从变量namef连接具有相同标签的点。


我认为geom_segment适合处理这种情况:

require(grid)
plt + geom_segment(aes(xend = position, yend = dgp), 
arrow = arrow(length = unit(0.1,"cm")))

最佳答案

geom_line将根据group美学来连接点,因此:

ggplot(mydata, aes(position, dgp, group = namef)) +   
  geom_point(size = 2, colour = "purple") +
  geom_line() +
  geom_text(data = mydata,aes(x=position,y=dgp + 0.05, label=namef))


得到你这个:



另外,通常最好将aes()调用放在对ggplot的原始调用中,然后仅在需要覆盖单个几何时才添加aes()data参数
一些美学。

关于r - 用r的ggplot2中的线连接点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11404959/

相关文章:

r - 在 R 中用点作为千位分隔符加载 csv 的最优雅的方法

R ggplot facet -- 共享 y 轴,多个不同的 x 轴

r - 使用 ggplot 创建多个堆叠的 fiddle 图

r - 在 map 上独立移动 2 个图例 ggplot2

python - 如何在Python中指定不同的第一个单词

r - 提取置信区间 data.table

r - 测试连接的问题

android - 在保持线条颜色的同时设置 EditText 的背景

r - 为什么 data.table 行索引上的 for 循环比 data.frame 慢?

windows - 如何从 Windows 命令行运行 Maxima