You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在ggplot地图添加另一数据框的德州城市标签时遇报错求助

解决ggplot添加城市标签时的.estimate未找到错误

问题背景

在绘制德州干旱相关空间地图时,尝试添加人口50万以上城市的名称标签,添加geom_text图层后触发以下错误:

Error in `geom_text()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 2nd layer.
Caused by error:
! object '.estimate' not found

错误原因

代码在ggplot()函数中定义了全局美学映射aes(fill = .estimate),该映射会被所有后续图层继承。但cities_data数据框中并不包含.estimate列,geom_text图层试图读取这个不存在的变量,因此报错。

解决方案

有两种可行的修复方式:

方式1:禁用图层的美学继承

给geom_text添加inherit.aes = FALSE参数,让它不继承全局的美学映射:

geom_text(color = 'black', data = cities_data, check_overlap = TRUE, 
          aes(x = long, y = lat, label = fixed_name), inherit.aes = FALSE)

方式2:将填充映射移至geom_sf内部

把fill = .estimate的映射从全局ggplot()中移到geom_sf的aes里,这样只有地图图层使用该映射,其他图层不受影响:

drought_sf %>%
  left_join(drought_rmse, by = 'GEOID') %>%
  ggplot() +
  geom_sf(aes(fill = .estimate), color = NA, alpha = 0.8) +
  labs(fill = "RMSE") +
  scale_fill_viridis_c(labels = scales::dollar_format()) +
  geom_text(color = 'black', data = cities_data, check_overlap = TRUE, aes(x = long, y = lat, label = fixed_name))

修改后的完整代码

# LOAD NECESSARY LIBRARIES
pacman::p_load(tidyverse,tidycensus,tidymodels,spatialsample,googleway,sf,maps) 

# IMPORT DROUGHT DATA
drought_raw <- read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-06-14/drought-fips.csv')

# PREPARE DROUGHT DATA: FILTER FOR TEXAS IN 2021 AND CALCULATE MEAN DSCI PER COUNTY
drought <- drought_raw %>%
  filter(State == "TX", lubridate::year(date) == 2021) %>%
  group_by(GEOID = FIPS) %>%
  # DSCI = Drought Severity and Coverage Index
  summarise(DSCI = mean(DSCI)) %>% 
  ungroup()

# GET MEDIAN INCOME DATA FROM THE ACS FOR TEXAS COUNTIES IN 2020
tx_median_rent <-
  get_acs(
    geography = "county",
    state = "TX",
    variables = "B19013_001", # Median household income
    year = 2020,
    geometry = TRUE  # Include county geometries for mapping
  )

# COMBINE DROUGHT AND MEDIAN INCOME DATA
drought_sf <- tx_median_rent %>% left_join(drought)

# VISUALIZE DROUGHT SEVERITY ACROSS TEXAS COUNTIES
drought_sf %>%
  ggplot(aes(fill = DSCI)) +
  geom_sf(alpha = 0.9, color = NA) +  # Use geom_sf to plot the county shapes
  scale_fill_viridis_c() # Use a viridis color scale

# VISUALIZE THE CORRELATION BETWEEN DROUGHT SCORE AND MEDIAN INCOME
drought_sf %>%
  ggplot(aes(DSCI, estimate)) +
  geom_point(size = 2, alpha = 0.8) +  # Scatter plot of DSCI vs. median income
  geom_smooth(method = "lm") +  # Add a linear regression line
  scale_y_continuous(labels = scales::dollar_format()) + # Format y-axis labels as dollars
  labs(x = "Drought score", y = "Median household income")

# CREATE SPATIAL CROSS-VALIDATION FOLDS
set.seed(123)  # Set seed for reproducibility
folds <- spatial_block_cv(drought_sf, v = 10)  # 10 spatial folds

# VISUALIZE THE SPATIAL FOLDS
folds
autoplot(folds) 
autoplot(folds$splits[[1]]) 

# BUILD AND EVALUATE A LINEAR REGRESSION MODEL
drought_res <-
  workflow(estimate ~ DSCI, linear_reg()) %>% # Define workflow with linear regression
  fit_resamples(folds, control = control_resamples(save_pred = TRUE)) # Fit model with spatial CV

# COLLECT MODEL PREDICTIONS
collect_predictions(drought_res) 
drought_res 
collect_predictions(drought_res) 

# CALCULATE ROOT MEAN SQUARED ERROR (RMSE) BY COUNTY
drought_rmse <-
  drought_sf %>%
  mutate(.row = row_number()) %>%
  left_join(collect_predictions(drought_res)) %>%  # Join predictions to original data
  group_by(GEOID) %>%
  rmse(estimate, .pred) %>%  # Calculate RMSE
  select(GEOID, .estimate)  # Select GEOID and RMSE estimate

cities_data <- us.cities %>% 
  filter(country.etc == 'TX' & pop > 500000)  %>% 
  mutate(fixed_name = str_replace(name,country.etc,''))

# 修复后的绘图代码(使用方式1:禁用继承)
drought_sf %>%
  left_join(drought_rmse, by = 'GEOID') %>%
  ggplot(
    aes(fill = .estimate)
    ) +
  geom_sf(color = NA, alpha = 0.8) +
  labs(fill = "RMSE") +
  scale_fill_viridis_c(labels = scales::dollar_format()) +
  geom_text(color = 'black', data = cities_data, check_overlap = TRUE, 
            aes(x = long, y = lat, label = fixed_name), inherit.aes = FALSE)

内容的提问来源于stack exchange,提问作者TheGoat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 19:31:02