5

I am trying to use plotly to make interactive ggplot2 maps.

In the code below I create a map of France with a different color for each departement :

library(tidyverse)
library(stringr)
library(stringi)
library(maps)
library(ggplot2)

map <- map_data("france")

map_theme <- theme(title=element_text(),
                   plot.title=element_text(margin=margin(20,20,20,20), size=18, hjust = 0.5),
                   axis.text.x=element_blank(),
                   axis.text.y=element_blank(),
                   axis.ticks=element_blank(),
                   axis.title.x=element_blank(),
                   axis.title.y=element_blank(),
                   panel.grid.major= element_blank(), 
                   panel.background= element_blank()) 

p = ggplot(map, aes(long,lat, group = group, fill = region)) +
  geom_polygon() +
  coord_map() +
  theme(legend.position = "none") +
  map_theme

plot(p)
ggplotly(p)

plot(p) and ggplotly(p) will give similar graphs, but the one provided with plotly appears stretched. It is problematic with a map. What would be the best strategy to avoid that ?

Lucas Morin
  • 373
  • 2
  • 11
  • 35

1 Answers1

1

Instead of using coord_map() you can try playing around with coord_fixed(). Its not perfect but it gets you a lot closer. My inspiration for this answer came from this thread: How to fix the aspect ratio in ggplot?

p2 = ggplot(map, aes(long,lat, group = group, fill = region)) +
  geom_polygon() +
  coord_fixed(1.50) +
  theme(legend.position = "none") +
  map_theme

plot(p2)
ggplotly(p2)
Patrick
  • 742
  • 7
  • 19