RStudio中使用ggplot2绘图时度数符号显示异常的解决办法
解决RStudio中ggplot坐标轴度数符号显示空白矩形的问题
问题描述
Windows 11 64位系统下,运行以下R代码绘制夏威夷岛屿地图时,ggplot生成的绘图里,坐标轴标签的度数符号(°)显示为空白矩形,且RStudio及所有包均已更新:
library(tidyverse) library(osmdata) bbx <- getbb("hawaii") border <- bbx %>% opq() %>% add_osm_feature(key = "place", value = c("island")) %>% osmdata_sf() border ggplot() + geom_sf( data = border$osm_lines, inherit.aes = FALSE, color = "black", size = .4, alpha = .8 )
解决方法
这是Windows系统默认字体不支持Unicode度数符号导致的问题,可通过以下方式解决:
- 指定支持Unicode的字体:在ggplot中为坐标轴文本设置支持度数符号的字体,比如Windows自带的
"Segoe UI"或"Arial Unicode MS"。修改代码如下:
ggplot() + geom_sf( data = border$osm_lines, inherit.aes = FALSE, color = "black", size = .4, alpha = .8 ) + theme( axis.text = element_text(family = "Segoe UI") )
- 自定义坐标轴标签:手动设置坐标轴标签,使用Unicode转义码
\u00B0来表示度数符号,确保符号能被正确渲染:
ggplot() + geom_sf( data = border$osm_lines, inherit.aes = FALSE, color = "black", size = .4, alpha = .8 ) + scale_x_continuous(labels = function(x) paste0(x, "\u00B0 W")) + scale_y_continuous(labels = function(x) paste0(x, "\u00B0 N"))
- 切换RStudio绘图设备:在RStudio设置中把默认绘图设备从
AGG改为Windows。操作路径:工具 -> 全局选项 -> 绘图 -> 设备,选择Windows后重启RStudio。
内容的提问来源于stack exchange,提问作者LastBorn
相关产品推荐
相关产品推荐

