首页 文章

ggplot2:将Shape,Color和Linestyle合并为一个图例

提问于
浏览
1

我想创建一个带有线条和条形的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"))

创建点,线和条形图的最小代码:

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))

初步结果:

Looks good so far

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

diagram + scale_colour_brewer(name="Line Legend",labels=c("Foo","Bar")) + scale_fill_brewer(name="Bar Legend",labels=c("Foo Bar","Bar Bar"))

产生不需要的结果

Problem: legend split into color, linestyle, shape

在最终结果中,两个所需的图例被分成三个 . 没有更多的传奇,其中颜色,线条样式和点形状是统一的 . 为什么?怎么解决这个?同样使用scale_colour_manual()和scale_shape_manual()会产生类似的结果 .

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

1 回答

  • 3

    我认为这符合您的要求:

    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"))
    

    看起来问题是图例中的形状和线条大小仍然用原始名称标记,因此您只需要添加指令以将其标记为与其他“线条图例”参数相同 .

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

相关问题