在R的ggplot中使用稻穗Unicode字符(U+1F33E)时出现无效序列错误
在R的ggplot中使用稻穗Unicode字符🌾(U+1F33E)的解决方法
问题说明
尝试用ggplot绘制包含稻穗字符🌾(U+1F33E)的图形时,使用转义序列"\u{1f33e}"会触发错误:Error: invalid \u{xxxx} sequence。但使用4位Unicode字符(如U+2620)的代码可正常运行,且已确认所用的Arial Unicode MS字体包含该稻穗字符。
可正常运行的示例代码(U+2620)
library(ggplot2) df <- read.table(text="x y 1 3 2 4 3 6 4 7 ", header=TRUE) ggplot(data = df, aes(x, y)) + geom_text(label="\u2620", size = 10, family = "Arial Unicode MS")
报错的稻穗字符代码
ggplot(data = df, aes(x, y)) + geom_text(label="\u{1f33e}", size = 10, family = "Arial Unicode MS")
错误信息:
Error: invalid \u{xxxx} sequence (line 2)
R会话信息
> sessionInfo() R version 4.0.2 (2020-06-22) Platform: x86_64-apple-darwin17.0 (64-bit) Running under: OS X 12.5.1 Matrix products: default LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib locale: [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] ggplot2_3.3.2 loaded via a namespace (and not attached): [1] magrittr_2.0.3 tidyselect_1.1.2 munsell_0.5.0 colorspace_2.0-2 [5] R6_2.5.1 rlang_1.0.2 fansi_1.0.3 blob_1.2.1 [9] dplyr_1.0.8 tools_4.0.2 grid_4.0.2 gtable_0.3.0 [13] utf8_1.2.2 cli_3.3.0 DBI_1.1.0 withr_2.5.0 [17] ellipsis_0.3.2 digest_0.6.29 assertthat_0.2.1 tibble_3.1.6 [21] lifecycle_1.0.1 farver_2.0.3 purrr_0.3.4 vctrs_0.4.1 [25] glue_1.6.2 labeling_0.3 compiler_4.0.2 pillar_1.8.1 [29] generics_0.1.3 scales_1.1.1 pkgconfig_2.0.3 > capabilities() jpeg png tiff tcltk X11 aqua http/ftp TRUE TRUE TRUE TRUE TRUE TRUE TRUE sockets libxml fifo cledit iconv NLS profmem TRUE TRUE TRUE TRUE TRUE TRUE TRUE cairo ICU long.double libcurl TRUE TRUE TRUE TRUE
解决方法
直接粘贴字符:跳过转义序列,直接把稻穗字符🌾粘贴到
label参数中:ggplot(data = df, aes(x, y)) + geom_text(label="🌾", size = 10, family = "Arial Unicode MS")使用
intToUtf8()生成字符:通过Unicode码点直接生成目标字符,避免转义错误:ggplot(data = df, aes(x, y)) + geom_text(label=intToUtf8(0x1F33E), size = 10, family = "Arial Unicode MS")更新R版本:你的R版本4.0.2对8位Unicode转义序列(
\u{xxxxxx})的支持不完善,更新到R 4.1及以上版本后,"\u{1f33e}"的写法即可正常使用。
内容的提问来源于stack exchange,提问作者Gopal Penny
相关产品推荐
相关产品推荐

