0

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")

enter image description here

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:

enter image description here

What I want is something like (other than the grid marks):

enter image description here

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")

enter image description here

bill999
  • 2,147
  • 8
  • 51
  • 103
  • Can you please edit your question to include sample data that doesn't require an API key to access. Otherwise it's difficult to test and help you. – MrFlick Oct 17 '20 at 02:46
  • I can't really tell what you are trying to do. Maybe you just want `theme_void()` and then also use `expand = c(0,0)` with `scale_x_continuous()` and `scale_y_continuous()` – MrFlick Oct 17 '20 at 02:49
  • I updated with another example that doesn't require a Census key. – bill999 Oct 17 '20 at 02:52
  • Your solution works well. Thanks! – bill999 Oct 17 '20 at 03:02

0 Answers0