Search code examples
rplotlypolygon

Adding polygon to plotly scatterplot


I created a plotly scatterplot in R on which I would like to add a polygon.

current plot

This is the code I used to make the graph:

fig <- plot_ly(data = data, x= ~xbeak, y = ~ybeak, color = ~coordsbeak, text = ~paste(coordsbeak), type = 'scatter')

Now I want to add a polygon to this plot, which I tried with add_polygons. The polygon is a different dataframe, consisting two columns with 42 x and y coordinates.

fig <- fig %>% add_polygons(x = xym$x, y=xym$y)

However when I try to run this I get this error which I don't understand. Any idea what I'm doing wrong?

Error: ! Tibble columns must have compatible sizes. • Size 42: Columns x and y. • Size 11149: Columns text and color. ℹ Only values of size one are recycled. Run rlang::last_error() to see where the error occurred.


Solution

  • Two solutions below. First, adding inherit = FALSE to add_plygons().

    library(tidyverse)
    library(plotly)
    xym<-data.frame(y=c(3,4,4,3),
                    x=c(5,5,6,6))
    fig <- plot_ly(data = iris, x= ~Sepal.Length, y = ~Sepal.Width, color = ~Species, text = ~paste(Species), type = 'scatter', mode="markers")
    fig <- fig %>% add_polygons(x = xym$x, y=xym$y, inherit = FALSE, showlegend = FALSE)
    fig
    

    Or, Switch the order of operations - make the polygons first, then the scatterplot.

    Here is an example with iris data:

    xym<-data.frame(x=c(5,5,6,6),
                    y=c(3,4,4,3))
    
    # make an empty plot_ly object
    fig <- plot_ly()
    # add the polygons
    fig<-fig %>% add_polygons(x = xym$x, y=xym$y)
    # add the scatterplot
    fig<-fig %>% add_trace(data = iris, x= ~Sepal.Length, y = ~Sepal.Width, color = ~Species, text = ~paste(Species), type ="scatter", mode="markers")
    fig
    

    referenced - Adding a polygon to a scatter plotly while retaining the hover info and Adding a polygon to a scatter plotly