Plotly: How do I set ylim and xlim for a map?
You are using coord_sf
which is intended for the special class of sf data frames rather than the polygons that come with ggplot
. You could use a package like rnaturalearth
to easily obtain data in this format. Here, I have selected a high-res image, but if you struggle to install rnaturalearthhires
, just select "medium" for map size.
library(ggplot2)
library(plotly)
library(rnaturalearth)
library(sf)
df <- ne_countries(country = c("United Kingdom", "Ireland", "France", "Norway"),
returnclass = "sf",
scale = "large")
map <- ggplot(df) +
geom_sf(color = "black", fill = "white") +
coord_sf(xlim = c(-12, 2), ylim = c(50, 60))
show(map)
and we get the plotly map like this:
visual <- ggplotly(map, height = 1.2 * 600, width = 600, tooltip=c("text"),
hoverinfo='hide', dynamicTicks = FALSE)
show(visual)
For information, if you're using R in Power BI service, this is how you do it:
You can get the desired result by adding a scaleratio to the xaxis option in layout (see code below).
library(maps)
library(ggplot2)
library(plotly)
boundaries <- ggplot2::map_data("world", region=c("UK","Ireland","France","Norway"))
map <- ggplot() +
geom_polygon(data=boundaries, aes(x=long, y=lat, group=group), color="black", fill="white") +
coord_sf(xlim=c(-12, 2), ylim=c(50,60))
show(map)
visual <- ggplotly(map, height=1.2*400, width=400, tooltip=c("text"), hoverinfo='hide',
dynamicTicks=F) %>%
layout(xaxis=list(scaleratio=0.6))
show(visual)
*Power BI service does not support rnaturalearth as per the accepted answer (https://docs.microsoft.com/en-us/power-bi/connect-data/service-r-packages-support)