title: How to plot line segments in ggplot2 when aesthetics do not have length 1 or same length as the data
body: <p>I' m trying to plot line segments with ggplot2 in order to make an example of a Miniminum Spanning Tree (MST).</p>
  
  <p>I'm able to do that with base R but I' m having problems when trying to enhance my plot with ggplot2.</p>
  
  <p>I have the following example:</p>
  
  <p><strong>w/ base R</strong></p>
  
  <pre><code># simulating data
  n=10
  set.seed(1984)
  d1&lt;-matrix(rnorm(n,mean=2,sd=1), n/2, 2)
  d2&lt;-matrix(rnorm(n,mean=-2,sd=.5), n/2, 2)
  d&lt;-rbind(d1,d2)
  
  # starting and ending points
  from&lt;-c(1,1,2,2,4,6,7,7,10)
  to&lt;-c(5,2,3,4,6,7,9,10,8)
  
  # plot
  plot(d[,1:2])
  segments(d[from,1], d[from,2], d[to,1], d[to,2],col="blue")
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/XiXyh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XiXyh.png" alt="enter image description here"></a></p>
  
  <p><strong>w/ ggplot2</strong></p>
  
  <pre><code>df&lt;-as.data.frame(d)
  library(ggplot2)
  b &lt;- ggplot(df, aes(df[,1], df[,2])) + geom_point()
  b + geom_segment(aes(x = df[from,1], y = df[from,2],
                 xend = df[to,1], yend = df[to,2]), colour="red", data = df)
  </code></pre>
  
  <p><strong>Edit</strong>: substituted colour="segment" by colour="red", since colour= "segment" does not make sense in this example.</p>
  
  <p>As you may notice, I've used the same logic from segments() function from base R, but ggplot complains about the length of my aesthetics, since it will be the length of data -1.</p>
  
  <blockquote>
    <p>Error: Aesthetics must be either length 1 or the same as the data (10): x, y, xend, yend, colour</p>
  </blockquote>
  
  <p>In <a href="http://ggplot2.tidyverse.org/reference/geom_segment.html" rel="nofollow noreferrer">http://ggplot2.tidyverse.org/reference/geom_segment.html</a> the logic seems to be valid but I still don't have any clue on how to handle the aesthetics length problem.</p>
  
  <p>I've read other related questions in Stack Overflow but I was not able to find a solution to my problem since my aesthetics will not have the same length of my data.</p>
  
  <p>Related questions:</p>
  
  <p><a href="https://stackoverflow.com/questions/44207090/aesthetics-must-be-either-length-1-or-the-same-as-the-data-207-x-y">Aesthetics must be either length 1 or the same as the data (207): x, y</a></p>
  
  <p><a href="https://stackoverflow.com/questions/42776133/error-aesthetics-must-be-either-length-1-or-the-same-as-the-data-10-x-y">Error: Aesthetics must be either length 1 or the same as the data (10): x, y</a></p>
  
  <p><a href="https://stackoverflow.com/questions/43551846/aesthetics-must-be-either-length-1-or-the-same-as-the-data-1">Aesthetics must be either length 1 or the same as the data (1)</a></p>