R语言ggplot绘图报错:无法识别Shapefile经纬度坐标求助
解决地图绘制报错的步骤
报错原因很明确:你的merged_data里没有名为long和lat的列,ggplot找不到对应坐标值。按以下步骤排查修正:
- 先查看数据集的所有列名,确认实际的经纬度字段:
# 查看列名 colnames(merged_data) # 或者查看更详细的数据结构 str(merged_data)
从输出里寻找类似经度(可能叫longitude、lon、x)和纬度(可能叫latitude、lat、y)的字段名。
- 将找到的实际字段名替换到ggplot代码的
aes()参数中。比如如果实际经度列是longitude,纬度列是latitude,修改后的代码如下:
ggplot() + geom_polygon(data = merged_data, aes(x = longitude, y = latitude, group = group, fill = Unemployment_Rate)) + labs(title = "Unemployment Rates in the U.S. (2015)", fill = "Unemployment Rate") + scale_fill_gradient(low = "white", high = "red") + theme_void()
- 额外提示:如果你的shapefile是用
sf包读取的(比如st_read()),数据会是sf格式的空间对象,此时用geom_sf()更简便,无需手动指定x/y坐标:
ggplot(merged_data) + geom_sf(aes(fill = Unemployment_Rate)) + labs(title = "Unemployment Rates in the U.S. (2015)", fill = "Unemployment Rate") + scale_fill_gradient(low = "white", high = "red") + theme_void()
内容的提问来源于stack exchange,提问作者Anisha Caynes
相关产品推荐
相关产品推荐

