Search code examples
rchartsplotlyradar-chart

R plotly: How to connect lines on polar/radar chart?


I am creating a polar chart in R with plotly, but I don't want the values between lines to be filled with color. I found the line_close property for python library, but I can't find the equivalent in R.

Chart code:

library(plotly)

p <- plot_ly(
  type = 'scatterpolar',
  mode = 'lines',
) %>%
  add_trace(
    mode = 'lines',
    r = c(3, 0, 1),
    theta = c('A','B','C'),
    name = '1'
  ) %>%
  add_trace(
    mode = 'lines',
    r = c(1, 2, 3),
    theta = c('A','B','C'),
    name = '2'
  ) %>%
  layout(
    polar = list(
      radialaxis = list(
        angle = 90,
        visible = T,
        range = c(0,3),
        showline = F,
        color = '#bfbfbf',
        nticks = 4,
        tickangle = 90
      )
    )
  )

p

Chart image:

enter image description here


Solution

  • I've had a good look through plotly::schema, and there doesn't seem to be an option to do this built in to the R port of plotly.

    However, it is trivial to define your own add_closed_trace function like this:

    add_closed_trace <- function(p, r, theta, ...) 
    {
      plotly::add_trace(p, r = c(r, r[1]), theta = c(theta, theta[1]), ...)
    }
    

    You can use this as a drop-in for add_trace, like this:

    library(plotly)
    
    p <- plot_ly(
      type = 'scatterpolar',
      mode = 'lines',
    ) %>%
      add_closed_trace(
        mode = 'lines',
        r = c(3, 0, 1),
        theta = c('A','B','C'),
        name = '1'
      ) %>%
      add_closed_trace(
        mode = 'lines',
        r = c(1, 2, 3),
        theta = c('A','B','C'),
        name = '2'
      ) %>%
      layout(
        polar = list(
          radialaxis = list(
            angle = 90,
            visible = T,
            range = c(0,3),
            showline = F,
            color = '#bfbfbf',
            nticks = 4,
            tickangle = 90
          )
        )
      )
    
    p
    

    enter image description here