[英]Adding ggplot2 legend
我一直在嘗試找到問題的答案,但是我在論壇中發現的問題無法解決。 我知道關鍵是正確的映射(或者至少這是我從以前的msg中了解的)。
這是我的代碼:
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))
我想用一個圖例來分隔“紅色”和“藍色”線...我該怎么做?
要將顏色顯示為圖例,可以添加一列顯示該類型,然后將其映射到geom_segment
的aes
。 最后,使用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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.