Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connecting points with lines in ggplot2 in r

Here is my data:

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

plt

I want to connect point with same label from variable namef. enter image description here

I thought geom_segment is appropriate to handle the situation:

require(grid)
plt + geom_segment(aes(xend = position, yend = dgp), 
arrow = arrow(length = unit(0.1,"cm")))
like image 969
jon Avatar asked Jul 10 '12 00:07

jon


People also ask

How do I join up points in ggplot2?

In ggplot2 we can add lines connecting two data points using geom_line() function and specifying which data points to connect inside aes() using group argument.

How do I connect points to a plot in R?

To add new points to an existing plot, use the points() function. The points function has many similar arguments to the plot() function, like x (for the x-coordinates), y (for the y-coordinates), and parameters like col (border color), cex (point size), and pch (symbol type).

What is geom_line in Ggplot?

geom_line() connects them in order of the variable on the x axis. geom_step() creates a stairstep plot, highlighting exactly when changes occur. The group aesthetic determines which cases are connected together.

What does geom_point () do in R?

The function geom_point() adds a layer of points to your plot, which creates a scatterplot.


1 Answers

geom_line will connect points according to the group aesthetic, so:

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

gets you this:

enter image description here

Also, it's generally better to put the aes() call in your original call to ggplot, and then only add an aes() or data argument to the individual geoms if you need to override some aesthetics.

like image 56
Marius Avatar answered Sep 29 '22 13:09

Marius