Black Lives Matter. Please consider donating to Black Girls Code today.

Plot_geo Unintended Behavior?

When using plot_geo on data which crosses the 180th meridian the add_lines function attempts to tie together the first and last data points, causing a weird behavior where the trace basically fabricates data and ruins the plot. Has anyone seen this behavior before or know a fix for it? I’ve provided an example below that can be copy / pasted.

# Generate data which crosses the 180 meridian
lon <- c(seq(1:179), -179, -178, -177)
lat <- rep(25, length(lon))

geo <- list(
  showland = TRUE,
  showlakes = TRUE,
  showcountries = TRUE,
  showocean = TRUE,
  countrywidth = 0.5,
  landcolor = toRGB("#90EE90"),
  lakecolor = toRGB("white"),
  oceancolor = toRGB("#F0F8FF"),
  projection = list(
    type = 'orthographic',
    rotation = list(
      lon = -60,
      lat = 20,
      roll = 0
    )
  ),
  lonaxis = list(
    showgrid = TRUE,
    gridcolor = toRGB("gray40"),
    gridwidth = 0.5
  ),
  lataxis = list(
    showgrid = TRUE,
    gridcolor = toRGB("gray40"),
    gridwidth = 0.5
  )
)

p <- plot_geo() %>%
  add_lines(x = lon, y = lat) %>% 
  layout(
    showlegend = FALSE, geo = geo,
    title = 'Contour lines over globe<br>(Click and drag to rotate)'
  )

p

For future “prosperity”, I have a stupid, inexplicable, hackish solution. If you add fake markers using add_markers and then set the markers inside an add_trace then plotly does exactly what it should do in the first place. I cannot even possibly fathom why this works.

image

# Generate data which crosses the 180 meridian
lon <- c(seq(1:179), -179, -178, -177)
lat <- rep(25, length(lon))

geo <- list(
  showland = TRUE,
  showlakes = TRUE,
  showcountries = TRUE,
  showocean = TRUE,
  countrywidth = 0.5,
  landcolor = toRGB("#90EE90"),
  lakecolor = toRGB("white"),
  oceancolor = toRGB("#F0F8FF"),
  projection = list(
    type = 'orthographic',
    rotation = list(
      lon = -60,
      lat = 20,
      roll = 0
    )
  ),
  lonaxis = list(
    showgrid = TRUE,
    gridcolor = toRGB("gray40"),
    gridwidth = 0.5
  ),
  lataxis = list(
    showgrid = TRUE,
    gridcolor = toRGB("gray40"),
    gridwidth = 0.5
  )
)

p <- plot_geo() %>%
  add_markers(x=0, y=0, alpha=0, size=30) %>%
  add_trace(x = lon, y = lat,
      marker = list(
        size=0.01
      ),
      line = list(
        dash = 'line',
        width = 2,
        color='royalblue'
      )
  ) %>%
  layout(
    showlegend = FALSE, geo = geo,
    title = 'Contour lines over globe<br>(Click and drag to rotate)'
  )

p