0

I've created a plot in R (see code below), but am unable to export the image with a transparent background. Is there any way to do this? I am using the following packages:

library(ggplot2)      
library(tidycensus)   
library(tmap)         
library(tmaptools)    
library(dplyr)        
library(sf)           

Once these are loaded, I execute the following code:

    census_api_key("581e11f28630d5911ef4cc16559d23128533046a", install = TRUE)

    dat19 <- get_acs("county", table = "B03001", year = 2019, output = "tidy", state = "TX", geometry = TRUE) %>% rename('2019' = estimate) %>% select(-moe)
    
    dat11 <- get_acs("county", table = "B03001", year = 2011, output = "tidy", state = "TX", geometry = FALSE) %>% rename('2011' = estimate) %>% select(-NAME, -moe)
    
    # process acs data
      
    dat <- left_join(dat19, dat11, by = c("GEOID", "variable"))
    st_geometry(dat) <- NULL # This drops the geometry and leaves a table
    
    
    dat <- mutate(dat,
                  cat = case_when(
                    variable %in% paste0("B03001_0",
                                         c("01")) ~ "poptot",
                    variable %in% paste0("B03001_0",
                                         c("03")) ~ "pophisp")) %>%
      filter(!is.na(cat))
    
    
    # summarize the data by county-year-category 
    
    dat <- tidyr::gather(dat, year, estimate, c(`2011`, `2019`))
    
    dat <- group_by(dat, GEOID, NAME, year, cat) %>%
      summarize(estimate = sum(estimate)) %>%
      ungroup() %>%
      tidyr::spread(cat, estimate) 
    
    # calculate final estimates 
    
    dat <- mutate(dat, est = (pophisp/poptot) * 100) %>%
      select(-c(poptot, pophisp)) %>%
      tidyr::spread(year, est) %>%
      mutate(diff = `2019`-`2011`)
    
    # initialize visualization of data using ggplot
    
    # distributions by year 
    
    datlong <- select(dat, -diff) %>%
      tidyr::gather(year, estimate, c(`2011`, `2019`)) %>%
      group_by(year) %>%
      mutate(med = round(median(estimate, na.rm = TRUE), 1))
    
    ggplot(datlong, aes(estimate)) +
      geom_histogram(fill = "firebrick2", 
                     color = "white", bins = 60) +
      xlab("Percent Hispanic by County (%)") +
      theme(plot.title = element_text(hjust = 0.5)) +
      facet_wrap(~year, ncol = 1) +
      geom_vline(aes(xintercept = med,
                     group = year), lty = "dashed") +
      geom_text(aes(label = paste("Median = ", med), x = med, y = 55))
    
    # counties with greatest change (+/-) in % hispanic population
    
    # We’re curious to know which counties experienced the largest increase or decrease in the % hispanic population. Use the function dplyr::top_n to get the first and last 10 records from the diff field.
    
    d10 <- top_n(dat, 10, diff) %>%
      mutate(type = "Hispanic population decreased",
             difftemp = diff)
    
    i10 <- top_n(dat, -10, diff) %>%
      mutate(type = "Hispanic population increased",
             difftemp = abs(diff))
    
    id10 <- bind_rows(list(i10, d10)) %>%
      arrange(desc(difftemp))
    
    ggplot(id10) + 
      geom_col(aes(x = forcats::fct_reorder(NAME, difftemp), 
                   y = difftemp, fill = type)) +
      coord_flip() +
      scale_fill_manual(values = c("firebrick2", "cyan4")) +
      theme(plot.title = element_text(hjust = 0.5),
            legend.position = "bottom",
            legend.title = element_blank()) +
      ggtitle("Counties with the greatest change (+/-) in
        Hispanic population, 2011-2019") +
      ylab("Difference in % insured (2019 - 2011)") +
      xlab("")
    
    # create a final geographic file for use with tmap
    
    shp <- dat19 %>%
      filter(variable == "B03001_001") %>% # much faster than using distinct()
    select(GEOID, NAME) %>%
      left_join(dat, by = c("GEOID", "NAME")) %>%
      arrange(GEOID) %>%
      rename(hispanic_2011 = `2011`,
             hispanic_2019 = `2019`,
             hispanic_diff = diff)

Following this, I use the following code to create the plot, after whichI will export and save using RStudio's built in functionality:

mymap <- tm_shape(shp) +
  tm_polygons(
    "hispanic_2011", #update year 2011, 2019
    palette = "BuPu",
    border.col = "black",
    border.alpha = 0.5,
    title = "Hispanic (%)"
  ) +
  tm_legend(legend.position = c("left", "bottom")) +
  tm_layout(
    frame = FALSE,
    bg.color = 'transparent',
    inner.margins = c(
      0.06,
      0.10,
      0.10,
      0.08),
      title = "Percent Hispanic by County, Texas 2011", #update year 2011, 2019
      title.size = 1.1,
      title.position = c("center", "top")
    )

mymap

I've tried implementing the following line to the code:

bg.color = NA,

Additionally, I've also added:

bg.color = "transparent",

However, the image saves with a white background, not a transparent one. I am needing to export the map and legends for use on an infographic.

Any help would be appreciated.

Phil
  • 5,491
  • 3
  • 26
  • 61
rfl026
  • 1
  • 1
  • Please add some data in order to make the question reproducible. [Helpful guidance for asking questions](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Peter Sep 22 '21 at 20:07
  • Hi Peter! Thank you for your guidance. I have updated the post with reproducible code/data. – rfl026 Sep 22 '21 at 20:30
  • Thankyou but the question is not reproducible as ` A Census API key is required. Obtain one at http://api.census.gov/data/key_signup.html, and then supply the key to the `census_api_key` function to use it throughout your tidycensus session` Maybe check out [MRE]? – Peter Sep 22 '21 at 20:33
  • I can't reproduce either, but try looking at [this answer](https://stackoverflow.com/a/41878833/16222617) – T. C. Nobel Sep 22 '21 at 20:37
  • I have added a censusapi key which can called using : census_api_key("581e11f28630d5911ef4cc16559d23128533046a", overwrite = TRUE) – rfl026 Sep 22 '21 at 21:10
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Sep 24 '21 at 09:15

0 Answers0