ggplotly maps faulty aspect ratio

Viewed 40

I am trying to make some interactive maps of the United States with basic tooltips using plotly. However, whenever I render the map the aspect ratio of the plot is 'off', the map looks like it has been stretched and it just looks odd.

library(readxl)
library(dplyr)
library(tidyr)
library(urbnmapr)
library(plotly)
library(ggplot2)

states_territory <- urbnmapr::get_urbn_map(map = "territories_states",
                                           sf = FALSE)

states_territory <- data.frame(states_territory)

states_territory %>%
  ggplot(aes_string(x = 'long', 
             y = 'lat', 
             group = 'group', 
             text = 'state_name')) +
    geom_polygon(color = "#ffffff", size = 0.25) +
    coord_map(projection = "albers", lat0 = 39, lat1 = 45) -> test_plot

plotly_plot <- ggplotly(test_plot,
                        tooltip = 'text')

plotly_plot

Rendering the code above should contain everything for a REPEX but please let me know if theres something I need to add.

This is a plot that will be inserted into a Shiny app, I have the app working but I am unable to get the plot to have the clean look Im hoping for.

If anyone has any suggestions to remedy this or any other interactive plotting methods, it would be much appreciated. I have already tried ggiraph, and while the plot looks nice, ggiraph does not autoscale in an R shiny context.

Thanks a bunch

1 Answers

This is a fairly simple fix, given the following function. I originally stole this function from a Q&A on SO. I don't know who I pilfered it from, though.

map_aspect = function(x, y) {
  x.center <- sum(range(x)) / 2
  y.center <- sum(range(y)) / 2
  x.dist <- ggplot2:::dist_central_angle(x.center + c(-0.5, 0.5), rep(y.center, 2))
  y.dist <- ggplot2:::dist_central_angle(rep(x.center, 2), y.center + c(-0.5, 0.5))
  y.dist / x.dist
}

You're going to replace coord_map with the following code to specify the aspect ratio in a way in which Plotly can inherit it.

coord_fixed(with(states_territory, map_aspect(long, lat)))

enter image description here

Related