gpt4 book ai didi

r - 在ggplot2中结合图例

转载 作者:行者123 更新时间:2023-12-04 13:59:10 24 4
gpt4 key购买 nike

我有多个 geom_point 的情节和一个stat_functionggplot2 .有没有办法显示单个图例?

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)

enter image description here

我想要一个带有蓝线和两种颜色形状的图例。我试过
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"))))

这导致:

enter image description here

关于r - 在ggplot2中结合图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33236495/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com