我一直试图找到我的问题的答案,但我无法用我在论坛中找到的解决方案。我知道正确映射的关键(或者至少这是我从以前的msgs中理解的)。
这是我的代码:
dat <- data.frame(
Individuals = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
Year = c(0, 5, 0, 0, 0, 0, 8, 0, 0, 3),
end = c(15, 10, 15, 6, 10, 8, 15, 6, 9, 5))
Person_time_R <- ggplot(dat) +
geom_segment(aes(x=Year, y=Individuals, xend=end, yend=Individuals),
color=c("blue","red","red","blue","red","red","blue","red","red","red"),
size=2) +
scale_y_reverse() +
ggtitle("Person-time") +
xlab("Years") +
ylab("Individuals") +
theme(
plot.title = element_text(hjust = 0.5, size=26, face="bold"),
axis.title.x = element_text(size=20),
axis.title.y = element_text(size=20)
) +
scale_y_discrete(limits=c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) +
scale_x_continuous(limits = c(0,16)) +
scale_x_discrete(limits=c( 0, 1, 3, 5, 7, 9, 11, 13, 15))
我希望有一个传说来分隔“红色”和“蓝色”线......我怎么能这样做?
答案 0 :(得分:1)
要将颜色显示为图例,您可以添加显示该类型的列,然后映射到aes
中的geom_segment
。最后,使用scale_color_manual
指定名称和颜色。
dat$Type <- c(1, 2, 2, 1, 2, 2, 1, 2, 2, 2)
ggplot(dat) +
geom_segment(aes(x=Year, y=Individuals, xend=end, yend=Individuals, colour = factor(Type)),
size = 2) +
scale_color_manual(values = c("blue", "red"), name = "Type")