【发布时间】:2019-07-19 03:14:19
【问题描述】:
我想在ggplot2 geom_point() 中使用Unicode 形状(具体来说,像↘、Unicode "\u2198" 或LaTeX \searrow 这样的箭头),如shape = "\u2198" 中的那些不在默认字体中的形状.在this unanswered post,@Laserhedvig commented“看来问题出在字体上。显然,基本默认字体不包含对这些特定字形的支持。现在,如何更改 geom_point() 的 shape 参数的字体?”
This solution 对于axes.text 中的Unicode 使用theme(axis.text.x = element_text(family = "FreeSerif")),而this solution 对所有theme(text=element_text(size=16, family="Comic Sans MS")) 使用text,但是我该如何为shape 执行此操作?
- 对于
shape使用Unicode 是否有通用解决方案? (我必须以某种方式使用cairo和/或字体family参数吗?) - 如果没有,是否还有其他一些箭头形状? (我对箭头形状和字形的搜索,包括在
scale_shapedocumentation 中的搜索结果都是空的。)
在我的例子中,我需要一个 ggplot2 层来显示跨离散类别的时间点变化方向的定性预测。
一个例子:
library(dplyr)
library(ggplot2)
d <- tibble(year = c(1, 1, 2, 2),
policy = rep( c('policy 1', 'policy 2'), 2),
prediction = c(NA, 'increase', 'decrease', NA),
predictionUnicode = c(NA, '\u2197', '\u2198', NA))
ggplot(d) +
geom_point(aes(x = year, y = policy, color = prediction), shape = "\u2198")
shape = "\u2198" (i.e. "↘") does not work
编辑:感谢 djangodude 对 ggplot 字体使用的评论,我找到了 geom_text 的 family 参数,它允许使用不同的字体。因此,Unicode“形状”可以绘制为带有geom_text 的字符。但是,geom_text 的图例是fixed to "a"。还有themes only control non-data display,所以base_family 参数不适用于shape。
ggplot(d) +
geom_tile( aes(x = year, y = policy), color = "black", fill = "white") +
# geom_point does not allow new fonts?
geom_point(aes(x = year, y = policy,
color = prediction), shape = "\u2198") +
# geom_text does allow new fonts, but the legend text is fixed to "a"
geom_text(aes(x = year, y= policy,
color = prediction,
label = predictionUnicode),
family = "Calibri") +
scale_x_continuous(breaks = c(1,2)) +
theme_gray(base_family = "Calibri")
geom_text plots unicode, but not in the legend
看来shape 参数确实是正确的方法,对吧?
我尝试将Sys.setenv(LANG = "en_US.UTF-8") 和Sys.setenv(LANG = "Unicode") 设置为无效,但也许某些全局语言设置会影响shape?
非常感谢您的帮助!
注意:这些 Unicode skull and crossbones 和 half-filled points 的解决方案没有图例,如果没有正确的字体,将无法工作:
要获得正确的字体:
查找包含您要查找的 Unicode 字符的已安装字体。我发现these instructions 很有帮助。
将安装的字体导入R
library(extrafont)
font_import()
fonts()
sessionInfo()
R version 3.5.2 (2018-12-20)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Mojave 10.14.3
【问题讨论】:
标签: r ggplot2 unicode fonts shapes