使用Unicode字符作为形状

时间:2018-10-20 06:14:00

标签: r ggplot2 unicode

我想使用unicode字符作为ggplot中图形的形状,但是由于未知原因,它们没有呈现。我确实找到了类似的查询here,但我也无法使该示例正常工作。

关于为什么的任何线索?

请注意,我不想将unicode字符用作“调色板”,我希望geom_point()绘制的每个项目都具有相同的形状(颜色将指示相关变量)。

运行

Sys.setenv(LANG = "en_US.UTF-8")

并重新启动R并没有帮助。在sprintf()中包装unicode也无济于事。

这是说明问题的代码示例:

library(tidyverse)
library(ggplot2)
library(Unicode)

p1 = ggplot(mtcars, aes(wt, mpg)) +
  geom_point(shape="\u25D2", colour="red", size=3) +
  geom_point(shape="\u25D3", colour="blue", size=3) + 
  theme_bw()

plot(p1)

这就是结果的呈现。

enter image description here

我使用macOS Sierra(10.13.6),R版本3.5.1和Rstudio 1.0.143。

感谢您的帮助!我一直在几个论坛上寻找解决方案,并将其发布到#Rstats上,到目前为止没有任何效果。解决方案可能隐藏在某个线程中的某个位置,但是如果这样,我将无法检测到它,并且我怀疑其他人也错过了它。所以,在这里,我要发表我的第一篇文章以使堆栈溢出:)

2 个答案:

答案 0 :(得分:4)

使用geom_text代替可以工作吗?它允许控制字体,因此您可以选择带有所需字形的字体。

library(tidyverse)
ggplot(mtcars, aes(wt, mpg)) +
  geom_text(label = "\u25D2", aes(color = as.character(gear)),  
            size=10, family = "Arial Unicode MS") +
  geom_text(label = "\u25D3", colour="blue", 
            size=10, family = "Arial Unicode MS") + 
  scale_color_discrete(name = "gear") +
  theme_bw()

enter image description here

答案 1 :(得分:1)

可以使用par更改字体系列。问题在于,这将影响基本R图形,但不会影响ggplot2图形,因为它们使用两种不同的图形设备(grDevicesgrid)。例如,我们可以尝试使用基本R函数来绘制示例,但起初我们会遇到相同的问题:

plot(mtcars$wt, mtcars$mpg, pch="\u25D2", col = "red", cex = 2)
points(mtcars$wt, mtcars$mpg, pch="\u25D3", col = "blue", cex = 2)

base R plot, unicode characters aren't rendered

如果我们先调用par(字体应包含符号),我们将得到想要的东西:

par(family = "Arial Unicode MS")
plot(mtcars$wt, mtcars$mpg, pch="\u25D2", col = "red", cex = 2)
points(mtcars$wt, mtcars$mpg, pch="\u25D3", col = "blue", cex = 2)

base R plot, unicode is rendered

更改专门影响ggplot geom_point中各点的字体系列参数似乎要复杂一些。据我所知,这将涉及将ggplot对象转换为grob,编辑参数然后进行绘制。使用Jon Spring的geom_text解决方案或使用基数R可能更有意义。