如何在ggplot中合并颜色,线条样式和形状图例

假设我在ggplot中有以下图表:


ggplot图


它是使用以下代码生成的:


x <- seq(0, 10, by = 0.2)

y1 <- sin(x)

y2 <- cos(x)

y3 <- cos(x + pi / 4)

y4 <- sin(x + pi / 4)

df1 <- data.frame(x, y = y1, Type = as.factor("sin"), Method = as.factor("method1"))

df2 <- data.frame(x, y = y2, Type = as.factor("cos"), Method = as.factor("method1"))

df3 <- data.frame(x, y = y3, Type = as.factor("cos"), Method = as.factor("method2"))

df4 <- data.frame(x, y = y4, Type = as.factor("sin"), Method = as.factor("method2"))


df.merged <- rbind(df1, df2, df3, df4)


ggplot(df.merged, aes(x, y, colour = interaction(Type, Method), linetype = Method, shape = Type)) + geom_line() + geom_point()

我只希望有一个图例可以正确显示形状,颜色和线型(interaction(类型,方法)图例最接近我想要的图例,但它没有正确的形状/线型) 。


我知道如果我使用scale_xxx_manual并且为所有图例指定了相同的标签,那么它们将被合并,但是我不想手动设置标签:如果有新的Method或Types,我不想拥有修改我的代码:想要一些通用的东西。


编辑

如以下答案所示,在这种特殊情况下,有几种方法可以完成工作。所有建议的解决方案都需要使用scale_xxx_manual functions或with guides函数手动设置图例线的类型和形状。


但是,建议的解决方案在一般情况下仍然不起作用:例如,如果我使用新的“ method3”方法向数据集添加新的数据框,则该方法不再起作用,我们必须手动添加新的图例形状和线型:


y5 <- sin(x - pi / 4)

df5 <- data.frame(x, y = y5, Type = as.factor("sin"), Method = as.factor("method3"))

df.merged <- rbind(df1, df2, df3, df4, df5)

override.shape <- c(16, 17, 16, 17, 16)

override.linetype <- c(1, 1, 3, 3, 4)


g <- ggplot(df.merged, aes(x, y, colour = interaction(Type, Method), linetype = Method, shape = Type)) + geom_line() + geom_point()

g <- g + guides(colour = guide_legend(override.aes = list(shape = override.shape, linetype = override.linetype)))

g <- g + scale_shape(guide = FALSE)

g <- g + scale_linetype(guide = FALSE)

print(g)

这给出:


5条曲线


现在的问题是:如何自动生成override.shape和override.linetype向量?


请注意,向量大小为5,因为我们有5条曲线,而interaction(Type, Method)因子的大小为6(我没有cos / method3组合的数据)


慕盖茨4494581
浏览 2508回答 3
3回答

白衣非少年

前几天我遇到了这个问题。图例中的R Cookbook部分说明:如果同时使用颜色和形状,则都需要为其指定比例尺规格。否则,将有两个两个单独的图例。在您的情况下,您需要shape和的规格linetype。编辑使用相同的数据创建形状颜色和线条非常重要,我通过直接定义列来组合了您的交互阶段。而不是scale_linetype_discrete创造传奇,我用scale_linetype_manual指定的值,因为它们将在四个不同的值,默认情况下。如果您想要所有可能的形状和线型的详细布局,请访问R Graphics网站以查看所有数字标识符:df.merged$int <- paste(df.merged$Type, df.merged$Method, sep=".")ggplot(df.merged, aes(x, y, colour = int, linetype=int, shape=int)) +&nbsp; geom_line() +&nbsp; geom_point() +&nbsp; scale_colour_discrete("") +&nbsp; scale_linetype_manual("", values=c(1,2,1,2)) +&nbsp; scale_shape_manual("", values=c(17,17,16,16))

富国沪深

labs()对于定义几何图形外观的所有美学使用并设置相同的值。library('ggplot2')ggplot(iris) +&nbsp;&nbsp; aes(x = Sepal.Length, y = Sepal.Width,&nbsp;&nbsp; &nbsp; &nbsp; color = Species, linetype = Species, shape = Species) +&nbsp; geom_line() +&nbsp; geom_point() +&nbsp; labs(color&nbsp; = "Guide name", linetype = "Guide name", shape = "Guide name")
打开App,查看更多内容
随时随地看视频慕课网APP