R: draw a line between two points in ggplot

I have a data frame that looks like this:

XY 100 50 80 60 70 90 110 60 30 20 ... ... 

More than 100 lines. Columns of columns X and Y are numeric

When I draw these points, I would like to draw a line between the first point (100.50) and any of the other points. In other words, I would like the line to connect (100.50) to (80.60), the line to connect (100.50) to (70.90), the line to connect (100.50) with (110, 60), but there is no line between (80.60) and (70.90). All lines start at the first point.

I do not have a third column. I can not use the group. I wonder if I can still build this graph in ggplot.

thanks

+5
source share
1 answer

The idea is to use a group. To do this, you need to add a third column that you can use to group. A possible way to achieve this is as follows.

First I define data samples

 df <- read.table(text = "XY 100 50 80 60 70 90 110 60 30 20", header = TRUE) 

Then I create a new data frame where the first row is repeated for each of the other rows. A grp column is grp that associates each repetition of the first row with one of the other rows:

 n <- nrow(df) - 1 new_data <- data.frame(X = c(rep(df$X[1], n), df$X[-1]), Y = c(rep(df$Y[1], n), df$Y[-1])) new_data$grp <- as.factor(rep(1:n, times = 2)) new_data ## XY grp ## 1 100 50 1 ## 2 100 50 2 ## 3 100 50 3 ## 4 100 50 4 ## 5 80 60 1 ## 6 70 90 2 ## 7 110 60 3 ## 8 30 20 4 

Now the chart can be created directly using ggplot:

 library(ggplot2) ggplot(new_data, aes(X, Y, group = grp)) + geom_point() + geom_line() 

enter image description here

An aesthetic group controls which points should be connected by a line. Since the grp column in new_data always combines the repetition of the first row with each of the other rows, the point corresponding to the first row is associated with each of the other points.

If you omit group = grp , a graph is drawn with one line going through all the points.

+8
source

Source: https://habr.com/ru/post/1238563/


All Articles