如何在R ggplot中动态绘制段(geom_segment)?

时间:2017-03-24 11:17:26

标签: r dynamic ggplot2 data-visualization

给定一组固定的点,我可以绘制它们并添加显式代码以将其中一些与geom_segment连接起来。如果我有一个单独的数据源包含所有段的坐标,有没有办法在同一个图中为这些段添加循环?

    ggplot() + 
      geom_point(data=cm,mapping = aes(x, y)) +
      # connect every two paired assets based on separate data source
      geom_segment (mapping=aes(x=10,y=10,xend=100,yend=100), arrow=arrow(angle = 8,type ="closed",length = unit(0.10, "inches")), 
size=0.2, linetype=1, color="#cccccc")
+ geom_segment ( ...

数据集:

x,y
10.0, 10.0
100.0, 100.0
...

区隔:

x,y,x2,y2
10.0, 10.0, 100.0,100.0
...

1 个答案:

答案 0 :(得分:3)

您可以为每个geom传递不同的数据源。在这种情况下:

ggplot() + 
      geom_point(data = cm, aes(x, y)) +
      geom_segment(data = segment, aes(x = x, y = y, xend = x2, yend = y2),
                   arrow = arrow(angle = 8,type = "closed",length = unit(0.10, "inches")), 
                   size = 0.2, 
                   linetype = 1,  
                   color = "#cccccc")