如何在标题为"工作单"下面的geom_segement图中添加标题。标题下面有一个红线,文字为#34; Type 1"和带文字的蓝线"类型2"?
谢谢。
df = data.frame(time1=as.POSIXct(c("2012-04-04 09:23:33","2012-04-04 11:33:55")),
time2=as.POSIXct(c("2012-04-04 10:05:04","2012-04-04 13:42:24")),
y1=c(1,2),
y2=c(1,2),
color = c("red","blue"))
ggplot(df) + geom_segment(aes(x = time1, y = y1, xend = time2, yend = y2),
colour= df$color, size = 4, data = df)
答案 0 :(得分:2)
将分组变量映射到color
中的aes
,并在scale_color_manual
中设置名称,值,分隔符和标签。
ggplot(df) +
geom_segment(aes(x = time1, y = y1, xend = time2, yend = y2, color = color),
size = 4, data = df) +
scale_color_manual(name = "work order", values = c("blue", "red"),
breaks = c("red", "blue"), labels = c("Type 1", "Type 2"))
您还可以使用scale_color_identity
,它允许跳过值的设置,但您需要包含guide = "legend"
,因为它默认为"none"
。
ggplot(df) +
geom_segment(aes(x = time1, y = y1, xend = time2, yend = y2, color = color),
size = 4, data = df) +
scale_color_identity(name = "work order", guide = "legend",
breaks = c("red", "blue"), labels = c("Type 1", "Type 2"))