Say that I use the following code to create the following plot, saved with ggsave
:
library(tidycensus)
library(tidyverse)
library(RColorBrewer)
options(tigris_use_cache = TRUE)
data0 <- get_acs(geography = "county",
variables = c(total="B15003_001", phd="B15003_025"),
year = 2017, geometry = TRUE, keep_geo_vars=TRUE)
data <- data0 %>% filter(STATEFP!="15"&STATEFP!="02"&STATEFP!="72") %>%
select(-moe) %>%
spread(variable, estimate) %>%
mutate(estimate = 100*(phd/total)) %>%
arrange(estimate)
data$GEOID <- as.integer(data$GEOID)
a <-ggplot() +
geom_sf(data = data, aes(fill = cut(estimate, c(0, 1, 2, 4, 20), include.lowest = TRUE)),
size=.005, show.legend = FALSE) +
scale_fill_brewer(type="seq", palette="RdYlGn", name="Percent", direction=-1) +
theme_bw() +[![enter image description here][1]][1]
theme(panel.background = element_rect(fill = 'white')) +
theme(panel.grid = element_blank(),axis.title = element_blank(),
axis.text = element_blank(),axis.ticks = element_blank(),
panel.border = element_blank())
ggsave(a, filename="phd_per.png",width=6,height=3.3,units='in',dpi=400, bg="gray")
My question is how can I save it so that there isn't all the extra white space around the image?
What I suspect is going on is that it is including the grid, which of course I don't want because I made it all white. When I remove this code:
theme(panel.background = element_rect(fill = 'white')) +
theme(panel.grid = element_blank(),axis.title = element_blank(),
axis.text = element_blank(),axis.ticks = element_blank(),
panel.border = element_blank())
I get this image:
What I want is something like (other than the grid marks):
UPDATE based on comment.
Here is another example, which does not require a Census key. All the above points remain the same:
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
b <- ggplot(nc) +
geom_sf(aes(fill = AREA))
ggsave(b, filename="nc.png",width=5.35,height=2.1,units='in',dpi=400, bg="gray")