ggplot2:将形状、颜色和线条样式合并为一个图例

Chr*_*ris 3 r legend ggplot2

我想创建一个带有线条和条形的 ggplot2 图表,可视化不同的 y 和 ybar 值。线条上覆盖有同样基于 y 值的点。最后应该有 2 个图例,一个用于线(+点)图,包括颜色、形状和线型,另一个用于条形图,包括填充颜色。线型、点形状和颜色根据变量类型(y1 或 y2)进行更改。这很有效,直到我想要手动设置图例名称和项目标签:

数据帧初始化的最少代码:

library(ggplot2)
library(reshape)
df = data.frame(c(10,20,40),c(0.1,0.2,0.3),c(0.1,0.4,0.5),c(0.05,0.1,0.2),c(0,0.2,0.4))
names(df)[1]="classes"
names(df)[2]="y1"
names(df)[3]="y2"
names(df)[4]="bary1"
names(df)[5]="bary2"
df$classes <- factor(df$classes,levels=c(10,20,40), labels=c("10m","20m","40m"))
Run Code Online (Sandbox Code Playgroud)

创建点图、线图和条形图的最少代码:

dfMelted <- melt(df)
diagram <- ggplot()
diagram <- diagram + theme_bw(base_size=16)
diagram <- diagram + geom_bar(data=subset(dfMelted,variable=="bary1" | variable=="bary2"), aes(x=factor(classes),y=value, fill=variable),stat="identity",position="dodge")
diagram <- diagram + geom_point(data=subset(dfMelted,variable=="y1" | variable=="y2"), size=4, aes(x=factor(classes),y=value, colour=variable, shape=variable)) 
diagram <- diagram + geom_line(data=subset(dfMelted,variable=="y1" | variable=="y2"), aes(x=factor(classes),y=value, group=variable, colour=variable, linetype=variable))
Run Code Online (Sandbox Code Playgroud)

初步结果:

到目前为止看起来不错

通过以下代码设置图例名称/项目标签:

diagram + scale_colour_brewer(name="Line Legend",labels=c("Foo","Bar")) + scale_fill_brewer(name="Bar Legend",labels=c("Foo Bar","Bar Bar"))
Run Code Online (Sandbox Code Playgroud)

产生不需要的结果:

问题:图例分为颜色、线条样式、形状

在最终结果中,两个所需的图例被分成了三个。不再有颜色、线型和点形状统一的图例。为什么?怎么解决这个问题呢?同样使用scale_colour_manual()和scale_shape_manual()会产生类似的结果。

我浏览了相关帖子,没有找到解决这种复杂情况的答案。

jan*_*ack 5

我认为这符合您的要求:

diagram + 
  scale_fill_brewer (name = "Bar Legend", labels = c("Foo Bar", "Bar Bar")) +
  scale_colour_brewer     (name = "Line Legend", labels = c("Foo", "Bar")) +
  scale_linetype_discrete (name = "Line Legend", labels = c("Foo", "Bar")) +
  scale_shape_discrete    (name = "Line Legend", labels = c("Foo", "Bar"))
Run Code Online (Sandbox Code Playgroud)

看起来问题在于形状和线条尺寸仍在图例中以其原始名称进行标记,因此您只需添加说明以将它们标记为与其他“线条图例”参数相同。

或者,当然,您可以重命名数据集中的变量......