r - ggplot2:如何将标尺的图例与解析的标签相结合?
问题描述
问题
在ggplot2
中,通常尽可能将不同比例的图例集成到单个组合图例中。到目前为止,这对我来说效果很好。但是,当我尝试解析比例标签以在图例中包含数学符号时,这似乎不起作用。
看这个例子:
# example data
d <- data.frame(x = 1:3, y = rep(0,3), f = c("a[1]", "a[2]", "a[3]"))
# plot
p <- ggplot(data = d, aes(x = x, y = y, color = f, shape = f)) +
geom_point() +
guides(
color = guide_legend(title = "F"),
shape = guide_legend(title = "F")
)
下面给出了具有形状/颜色的自定义值以及按预期组合的图例的图。
# plot + custom shapes/colors
p +
scale_color_manual(name = "F", values = c("red", "blue", "green")) +
scale_shape_manual(name = "F", values = c(16, 15, 18))
但是,在解析标签时,标签按预期出来了,但图例不再合并。
# plot + custom shapes/colors + parsed labels
parse.labels <- function(x) parse(text = x)
p +
scale_color_manual(name = "F", labels = parse.labels, values = c("red", "blue", "green")) +
scale_shape_manual(name = "F", labels = parse.labels, values = c(16, 15, 18))
请注意,结果与scale_._discrete
而不是相同scale_._manual
。同样,为两个比例指定相同的名称guides(shape = guide_legend(title = "F"), color = guide_legend(title = "F"))
不会改变这种行为。
问题
如何在维护解析标签的同时整合两个图例?
解决方案
我建议使用labels
in 参数scale_*_discrete()
并将您的标签值保存在新向量中的这种方法:
library(ggplot2)
# example data
d <- data.frame(x = 1:3, y = rep(0,3), f = c("a[1]", "a[2]", "a[3]"))
#Labs
lab1 <- c(expression(a[1]),
expression(a[2]),
expression(a[3]))
# plot
ggplot(data = d, aes(x = x, y = y, color = f, shape = f)) +
geom_point() +
guides(
color = guide_legend(title = "F"),
shape = guide_legend(title = "F")
)+
scale_color_discrete(labels = lab1) +
scale_shape_discrete(labels = lab1)
输出:
推荐阅读
- makefile - 通过静态库检查 make 依赖项
- reactjs - 是否可以使用 DOM 测试库对反应应用程序进行端到端测试
- python-3.x - Why Doesn't Anything Return When Calling the Print() from a Class?
- c++ - getline 出错(我相信),在获取管道程序的输入时抛出 std::logic_error
- python - 使用 pandas 根据其他列中的值连接值
- laravel - Laravel Api 未从请求类发送所需的错误 json 消息
- django - 来自数据库的查询结果在分页上消失:Django
- intellij-idea - 如何在 Thymeleaf 链接标签中转义“@”字符?
- python-3.x - docker run not working:尽管制作了容器映像,但没有创建容器
- html - Django - CSS 文件未正确链接到模板