r - 为功能组合添加手动 ggplot 图例
问题描述
如何为以下每一行添加带有标签的手动图例:
lty=1, lwd=2, color='black', label='Litigating'
lty=2, lwd=2, color='black', label='Non-litigating'
lty=1, lwd=1, color='gray', label='Reference'
这是一个丑陋的模型来传达这个想法。标签的确切位置并不重要。我只想要每行一个图标。
这是我尝试制作的一种方法,但图例按功能展开,产生六个图标而不是三个:
# Make a data.frame with 10 points and the aesthetics associated wit each
D_legend = data.frame(
x = 1:10,
y = rnorm(10),
lwd = factor(c(2,2,2,2,2,2,1,1,1,1)),
lty = factor(c(1,1,1,2,2,2,1,1,1,1)),
color=c(rep('black', 6), rep('gray', 4))
)
# Plot it. I want a nice legend here!
ggplot(D_legend, aes(x=x, y=y, lty=lty, lwd=lwd, color=color)) +
geom_line() +
theme(legend.position="top")
解决方案
让我们简单地创建一个确定线类型的交互变量:
D_legend$type <- droplevels(with(D_legend, interaction(lty, lwd, color)))
# Giving better names
levels(D_legend$type) <- c("Litigating", "Non-litigating", "Reference")
现在我们可以分别处理这三种美学:
ggplot(D_legend, aes(x = x, y = y, lty = type, lwd = type, color = type)) +
geom_line() + theme(legend.key.width = unit(2, "cm")) +
scale_linetype_manual(
NULL,
values = c("Litigating" = 1, "Non-litigating" = 2, "Reference" = 1)
) +
scale_size_manual(
NULL,
values = c("Litigating" = 2, "Non-litigating" = 2, "Reference" = 1)
) +
scale_color_manual(
NULL,
values = c("Litigating" = "black", "Non-litigating" = "black", "Reference" = "gray")
)
我增加legend.key.width
了,否则第二行类型是虚线是不可见的。如果您希望图例有一个名称,则用type
它替换,这样您也可以删除所有NULL
.
推荐阅读
- javascript - 递归函数求解
- python - 如何构建一个简单的分词器
- r - 通过SQL从数据库导入数据时如何让注册商标标志在R中正确显示
- c# - Type.GetType(“{namespace.classname}{assemblyname}”) 在 C# 中不起作用
- r - 使用 If 函数,如何将数据框中的文本字符串更改为另一个字符串?
- batch-file - 从 .bat 脚本模拟 CMD 提示的最佳方法
- windows - 动态更改文件扩展名外观
- windows - 为什么我的 IP 随机开始默认为 IPv6(以及我的私有 IP 更改)?
- java - 重新运行时将替换保存到文件的输入
- typescript - 打字稿 - 类型“未定义”不可分配给类型“字符串 | 号码 | 象征'