ggplot2:将线宽应用于图例键 [英] ggplot2: applying width of line to the legend key
问题描述
考虑data.frame"dfc":
Considering the data.frame "dfc":
dfc <- structure(list(lag = c(-5L, -4L, -3L, -2L, -1L, 0L, 1L, 2L, 3L,
4L, 5L, -5L, -4L, -3L, -2L, -1L, 0L, 1L, 2L, 3L, 4L, 5L), variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("var1", "var2"), class = "factor"),
value = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0.6, 1.2, 1.8,
2.4, 3, 3.6, 4.2, 4.8, 5.4, 6, 6.6), size = c(2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)), .Names = c("lag",
"variable", "value", "size"), row.names = c(NA, -22L), class = "data.frame")
外观如下:
head(dfc)
lag variable value size
1 -5 var1 1 2
2 -4 var1 2 2
3 -3 var1 3 2
4 -2 var1 4 2
5 -1 var1 5 2
6 0 var1 6 2
我想用不同的线型(取决于变量")和宽度(取决于"size")针对滞后"绘制值".我用这段代码实现了:
I would like to plot "value" against "lag" with different line styles (depending on "variable) and widths (depending on "size"). I achieved with this piece of code:
ggplot(dfc) +
geom_line(aes(x = lag, y = value, linetype = variable, size = size)) +
scale_size(range=c(1, 2), guide=FALSE) +
scale_linetype_manual(values = 1:2, labels = c("Name of var1 ", "Name of var2")) +
theme(legend.title = element_blank(), legend.position = "bottom",
legend.direction = "horizontal")
给出该图:
但是我无法弄清楚如何相应地更改图例中行的大小并保持重命名.
But I cannot figure out how, at the same, to change the size of the line inside the legend, accordingly, and to keep the renaming.
推荐答案
z <- ggplot(dfc) +
geom_line(aes(x = lag, y = value, linetype = variable, size = size)) +
scale_size(range=c(1, 2), guide=FALSE)
z <- z + theme(legend.key.width = unit(5,"cm"))
z <- z + guides(linetype = guide_legend(override.aes = list(size = 2)))
z
我已经将guides()
函数添加到了先前的答案中.
I have added the guides()
function to my previous answer.
增加legend.key.width
的宽度后,可以通过使用override.aes
参数并将其分配给linetype
变量来更改图例中行的大小.
After increasing the width of the legend.key.width
, size of the lines in the legend can be changed by using the override.aes
parameter and assigning it to the linetype
variable.
这可以是@cogitovita提出的其他方式.
This can be other way than what @cogitovita proposed.
这篇关于ggplot2:将线宽应用于图例键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!