0

Is there any way I can select some points on a plot generated by ggplot or ggplotly, and then these points get connected by lines.

I want to use this in a shiny app that I am developing, in which, the app is generating a graph, and I want the user to select some points on the scatterplot, and then the app should be able to connect those points by lines.

1 Answers1

1

How many points will the user be connecting? What general interface are you using?

I assume you'll grab the x,y coordinates for "point1" and "point2". One approach such as the following my be helpful:

# example data
df <- data.frame(x=sample(1:10, 5) ,y=sample(1:10, 5))

# example plot without lines
ggplot(df, aes(x,y)) + xlim(0,10) + ylim(0,10) +
    geom_point(color='red', size=3)

enter image description here

Here's an example function that would take input of two points (x1,y1 and x2,y2), then connect them via geom_segment. If you wanted a curved line, you could use geom_curve, and potentially some logic to decide how to draw the curve.

drawPlot <- function(x1, y1, x2, y2) {
    ggplot(df, aes(x,y)) + xlim(0,10) + ylim(0,10) +
        geom_segment(aes(x=x1, y=y1, xend=x2, yend=y2)) +
        geom_point(color='red', size=3)

}

Let's pass it two points:

drawPlot(3,9, 7,6)

enter image description here

The problem with the above solution is that it only connects two points. Not sure if that works for you, so the alternative scalable version would be to connect multiple points:

drawPlotLine <- function(user_selected) {
    ggplot(df, aes(x,y)) + xlim(0,10) + ylim(0,10) +
        geom_line(data=user_selected) +
        geom_point(color='red', size=3)

}

Here, you would pass a user-selected subset of points. Depending on your preference, the user may "brush select"(drag select with a box) or click individual points to select them. Save those selected points as a subset of the original dataframe, then pass that to geom_line:

user_df <- df[c(1,4,3),]
drawPlotLine(user_df)

enter image description here

chemdork123
  • 12,369
  • 2
  • 16
  • 32
  • I want the user to select at least 5 points on the plot and my shiny app should be able to connect them all. And one more thing you should know is that the user is uploading the data file in the shiny app, that gets rendered in the table form in the app and then the graph is plotted by plotly. – Kshitij15571 May 02 '20 at 18:04
  • So, the coding should be all in the form of variables, because the user won't be selecting the same points for every plot. User should be able to select any random 5 points and I am thinking of introducing a button named 'connect', after pressing that button all the selected points should get connected. – Kshitij15571 May 02 '20 at 18:10