library(tmap)

## EXAMPLE 2 ---------------------------------------------------------------

# Step 1: join attributes
library(dplyr)
data("us_states", "us_states_df", package = "spData")
us_states <- left_join(us_states, us_states_df, by = c("NAME" = "state"))

tm_shape(us_states) +
  tm_polygons(fill = "median_income_15")

# Step 2: add projection and title

tm_shape(us_states) +
  tm_polygons(
    fill = "median_income_15",
    fill.legend = tm_legend(title = "", position = c("left", "bottom"))
  ) +
  tm_crs("auto") +
  tm_title("Median Income in 2015 (USD)")

# Step 3: update the color scale
med_inc15 <- median(us_states$median_income_15, na.rm = TRUE)

tm_shape(us_states) +
  tm_polygons(
    fill = "median_income_15",
    fill.scale = tm_scale_continuous(midpoint = med_inc15),
    fill.legend = tm_legend(title = "", position = c("left", "bottom"), reverse = TRUE)
  ) +
  tm_crs("auto") +
  tm_title("Median Income in 2015 (USD)")

tm_us1 <- tm_shape(us_states) +
  tm_polygons(
    fill = "median_income_15",
    fill.scale = tm_scale_continuous(midpoint = med_inc15),
    fill.legend = tm_legend(
      title = "",
      orientation = "landscape",
      frame = FALSE,
      width = 60,
      position = tm_pos_out("center", "bottom", "center")
    )
  ) +
  tm_crs("auto") +
  tm_title("Median Income in 2015 (USD)")

tm_us1

# Optional: interactive preview (remember to reset)
tmap_mode("view")
tm_us1
tmap_mode("plot")

# Step 4: add more map elements

tm_us2 <- tm_us1 +
  tm_text(
    "NAME",
    size = "AREA",
    size.scale = tm_scale_continuous(values.scale = 1.3),
    size.legend = tm_legend(show = FALSE)
  ) +
  tm_scalebar(position = c("left", "bottom")) +
  # tm_compass() +
  # Optional: local logo file if available
  # tm_logo("figs/Rlogo.png", height = 2) +
  tm_credits("Source: US Census Bureau", position = c("left", "bottom"))

tm_us2

# Optional: add a minimap

tm_us2 + 
  tm_minimap(position = tm_pos_out())
