2

I currently have a ggplot of multiple shapefiles that are cropped to be inside a certain bounding box. I want to draw a complete box around the entire region, but the portions of the plot that crop out a shapefile polygon (Mexico's southern edge & Canada's northern edge) won't include the box.

pl = ggplot() +
  geom_sf(data = state_union, aes(fill = data)) +
  geom_sf(data = counties_thisState, aes(fill = data), color = "gray") +
  geom_sf(data = state_union, fill = NA) +
  geom_sf(data = canada, fill = "lightgray") +
  geom_sf(data = mexico, fill = "lightgray") + 
  coord_sf(xlim = c(-126, -66), ylim = c(22, 53), expand = FALSE) +
  scale_fill_manual(values = colors,
                    labels = c("0", "> 0 - 5.9", "6.0 - 20.9",
                               "21.0 - 50.9", "51.0 - 99.9", "> 100",
                               "States without reporting")) +
  annotation_scale(location = "br", width_hint = 0.2) +
  annotation_north_arrow(location = "br", which_north = "true",
                         pad_x = unit(0.5, "in"), pad_y = unit(0.25, "in"),
                         style = north_arrow_fancy_orienteering) +
  xlab("Longitude") + ylab("Latitude") +
  labs(title = "Title", 
  fill = "Fill") +
  theme(panel.background = element_rect(color = "black", fill = NA))

Result of above code

I thought that including the theme after all the geom_sf functions would have the box be drawn completely over the polygons but this isn't the case.

Andy G
  • 21
  • 1
  • Welcome to StackOverflow. Can you provide some example data that will let us reproduce the image you see in "result of above code" or a simplified version of it? Without a minimal reproducible example it is somewhat difficulty to help. – socialscientist Jul 21 '22 at 20:05

1 Answers1

1

It is difficult to know for sure without a reproducible working example, but my best guess is that the issue arises from using panel.background rather than panel.border. The latter draws on the top layer, the former draws on the bottom layer.

library(ggplot2)

# Example data
df <- data.frame(x = 1:10, y = 1:10)

Make plot - panel.border

Note that white dashes on the border.

ggplot(df, aes(x=x, y=y)) +
  geom_point() +
  theme(panel.background = element_rect(color = "#1b98e0",
                                    fill = NA,
                                    size = 1))

Make plot - panel.border

Note that white dashes on the border are gone.

ggplot(df, aes(x=x, y=y)) +
  geom_point() +
  theme(panel.border = element_rect(color = "#1b98e0",
                                  fill = NA,
                                  size = 1))

socialscientist
  • 3,759
  • 5
  • 23
  • 58