我有一个有两行的情节,其中图例条目非常相似,除了一些单词(见下文)。
我的代码如下所示:
library(tidyverse)
set.seed(36)
Data <- data.frame(
date = sample((as.Date(as.Date("2011-12-30"):as.Date("2012-01-04"),
origin="1970-01-01")), 1000, replace = TRUE),
group = sample(c("0", "1"), 1000, replace = TRUE),
outcome = sample(c("0", "1"), 1000, replace = TRUE))
Data %>%
mutate(date = as.POSIXct(date), group = factor(group)) %>%
group_by(group, date) %>% #group
summarise(prop = sum(outcome == "1")/n()) %>% #calculate proportion
ggplot()+
geom_line(aes(x = date, y = prop, color = group))+
geom_point(aes(x = date, y = prop, color = group)) +
scale_color_manual(values = c("0" = "blue", "1" = "black"), labels = c("0" = 'Some text that repeats, the only unique thing being "A"', "1" = 'Some text that repeats, the only unique thing being "B"'), name = "Legend")
我想简化传说。它应包含以下几行:
答案 0 :(得分:1)
以下是提案:
scale_color_manual(values = c("0" = "blue", "1" = "black"),
labels = c("0" = '"A"', "1" = '"B"'),
name = "Legend\nSome text that repeats,\nthe only unique thing being")
但我会删除"Legend"
(不是非常有用的恕我直言)。
要明确区分"Legend"
和字幕文字,您可以使用expression
和atop
加粗:
legend_title = expression(atop(bold("Legend\n"),
"Some text that repeats,\nthe only unique thing being"))
Data %>%
mutate(date = as.POSIXct(date), group = factor(group)) %>%
group_by(group, date) %>% #group
summarise(prop = sum(outcome == "1")/n()) %>% #calculate proportion
ggplot()+
geom_line(aes(x = date, y = prop, color = group))+
geom_point(aes(x = date, y = prop, color = group)) +
scale_color_manual(values = c("0" = "blue", "1" = "black"),
labels = c("0" = '"A"', "1" = '"B"'),
name = legend_title)
然后您可以在"Legend"
之后添加空格以将其对齐到左侧:
legend_title = expression(atop(bold("Legend \n"),
"Some text that repeats,\nthe only unique thing being"))
答案 1 :(得分:1)
这是一种方法,只是略显苛刻:使用group
中的fct_expand
(包含在tidyverse中)为您的forcats
变量添加虚拟级别,然后使用fct_relevel
来使它成为因素的第一级。这样,您就会在图例顶部列出一个虚假的观察结果,但实际上并没有附带任何数据。
除了添加该行之外,我唯一改变的是drop = F
色标,因此即使没有与虚拟关卡相关的数据,它仍会显示在图例中,然后显示图例标签。 / p>
一个缺点是虚拟变量的图例键是可见的;可能有一些方法可以摆脱它,或者你可以通过给图例键设置白色背景来降低它的可见度。
library(tidyverse)
set.seed(36)
Data <- data.frame(
date = sample((as.Date(as.Date("2011-12-30"):as.Date("2012-01-04"),
origin="1970-01-01")), 1000, replace = TRUE),
group = sample(c("0", "1"), 1000, replace = TRUE),
outcome = sample(c("0", "1"), 1000, replace = TRUE))
Data %>%
mutate(date = as.POSIXct(date), group = factor(group)) %>%
# add a dummy factor level & make it the first level
mutate(group = group %>% fct_expand("dummy") %>% fct_relevel("dummy")) %>%
group_by(group, date) %>% #group
summarise(prop = sum(outcome == "1")/n()) %>% #calculate proportion
ggplot()+
geom_line(aes(x = date, y = prop, color = group))+
geom_point(aes(x = date, y = prop, color = group)) +
scale_color_manual(values = c("0" = "blue", "1" = "black", "dummy" = "transparent"), labels = c("0" = "A", "1" = "B", "dummy" = "Some text that repeats,\nthe only unique thing being"), name = "Legend", drop = F)
由reprex package(v0.2.0)创建于2018-04-09。