使用以下代码:
plt <- ggplot(data) + geom_step(aes(factor(no), var7, color = group_no, group = group_no), size = 1.6)
plt + geom_step(aes(factor(no), var5, color = group_no, group = group_no), linetype = 'dashed', size = .7)
现在我想以下列方式之一修改图例:
可行吗?我试过scale_linetype_manual(values = c('var5', 'var7')
,但它没有用。
数据如下所示:
data <- structure(list(no = c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L), group_no = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("1", "2"), class = "factor"), var1 = c(2, 1, 1, 1, 1, 0, 1, 1), var2 = c(0, 0, 1, 1, 1,
0, 1, 0), var3 = c(2.04466646181187, 0.660598114091747, 1.55142947390572,
1.53055726052766, 1.33062973767801, 0.521466633696396, 0.383486796026974,
0.320273289219046), var4 = c(0.786548055557462, 0.933132594335315,
0.734844331310191, 0.404908113668656, 0.50963171017644, 0.066048513105941,
0.156065948976073, 0.528480184907794), var5 = c(2, 1, 3,
2, 4, 2, 5, 3), var6 = c(0, 0, 1, 1, 2, 1, 3, 1), var7 = c(2.04466646181187,
0.660598114091747, 3.59609593571759, 2.19115537461941, 4.92672567339561,
2.71262200831581, 5.31021246942258, 3.03289529753485), var8 = c(0.786548055557462,
0.933132594335315, 1.52139238686765, 1.33804070800397, 2.03102409704409,
1.40408922110991, 2.18709004602017, 1.93256940601771)), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, -8L), vars = "group_no", drop = TRUE, .Names = c("no", "group_no", "var1", "var2", "var3", "var4", "var5", "var6", "var7", "var8"), indices = list(c(0L, 2L, 4L, 6L), c(1L, 3L, 5L, 7L)), group_sizes = c(4L, 4L), biggest_group_size = 4L, labels = structure(list(group_no = structure(1:2, .Label = c("1", "2"), class = "factor")), class = "data.frame", row.names = c(NA, -2L), vars = "group_no", drop = TRUE, .Names = "group_no"))
答案 0 :(得分:1)
如果我理解正确,这是您第一次请求的选项
library(tidyverse)
data %>%
gather(variable, value, c(var5, var7)) %>%
ggplot() +
geom_step(aes(factor(no),
value,
color = group_no,
linetype = variable,
group = interaction(group_no, variable),
size = variable)) +
scale_linetype_manual(values = c('var5' = "dashed",
'var7' = "solid")) +
scale_size_manual(values = c('var5' = 1,
'var7' = 2)) +
guides(size = "none")
将数据从宽格式转换为长格式,并将color
映射到&#39; group_no&#39;和linetype
到&#39;变量&#39;。 interaction
是必要的,因为该组不再由单个变量定义,而是由组合&#39; group_no&#39;组合而成。和&#39;变量&#39;。
在映射&#39;变量&#39;后,使用size
更改行的scale_size_manual
这种美学。添加+ guides(size = "none")
,以便图例中不会显示size
的不同geom_step
。