[英]Combine legend in ggplot2
我在ggplot2
有一個多個geom_point
和一個stat_function
的ggplot2
。 有沒有辦法展示一個傳奇?
df <- data.frame("x"=c(1:5), "a"=c(1,2,3,3,3), "b"=c(1,1.1,1.3,1.5,1.5))
df <- melt(df, "x")
p <- ggplot(df, aes(x=x, y=value)) +
geom_point(aes(colour=variable, shape=variable)) +
stat_function(aes(colour="log2(x)"), fun=log2)
我希望有一個藍色線條和兩個彩色形狀的傳奇。 我試過了
scale_colour_discrete(name="legend", breaks=c("a", "b", "log2(x)")) +
scale_shape_discrete(name="legend", breaks=c("a", "b"))
但這不起作用。 有沒有辦法自動或手動執行此操作?
提前致謝。
可能更容易的替代方法是使用override.aes
,如下所示:
ggplot(df, aes(x = x, y = value)) +
geom_point(aes(colour = variable, shape = variable), size = 3) +
stat_function(aes(colour = "log2(x)"), fun = log2, size = 1.5) +
guides(shape = FALSE,
colour = guide_legend(override.aes = list(shape = c(16, 17, NA),
linetype = c("blank", "blank", "solid"))))
這導致:
指定一個.
作為曲線的形狀符號和點的空白行:
p <- ggplot(df, aes(x=x, y=value)) +
geom_point(aes(colour=variable, shape=variable, linetype = variable), size = 3) +
stat_function(aes(colour="log2(x)", shape = "log2(x)", linetype = "log2(x)"), fun=log2) +
scale_shape_manual(values = setNames(c(16, 17, 46), c("a", "b", "log2(x)"))) +
scale_linetype_manual(values = setNames(c(0, 0, 1), c("a", "b", "log2(x)")))
print(p)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.