【问题标题】:Ggplot with more than two legends具有两个以上图例的ggplot
【发布时间】:2017-05-13 14:04:05
【问题描述】:

我有一个data.frame,我想使用ggplot 散点图。 数据有 3 个factors 我想在图例中显示它们的级别,尽管点的颜色将仅根据这些因素之一(下面的df$group)。

这是我目前所拥有的:

set.seed(1)
df <- data.frame(x=rnorm(100),y=rnorm(100),
                 group=LETTERS[sample(5,100,replace=T)],
                 type=letters[sample(3,100,replace=T)],
                 background=sample(4,100,replace=T),stringsAsFactors=F)

df$group <- factor(df$group,LETTERS[1:5])
df$type <- factor(df$type,;etters[1:3])
df$background <- factor(df$background,c(1:4))

我手动指定颜色:

require(RColorBrewer)
require(scales)
all.colors <- hcl(h=seq(0,(12-1)/(12),length=12)*360,c=100,l=65,fixup=TRUE)
group.colors <- all.colors[1:5]
type.colors <- all.colors[6:8]
background.colors <- all.colors[9:12]

这就是我在图例中显示 3 factors 的内容(df$groupdf$type):

require(ggplot2)

ggplot(df,aes(x=x,y=y,colour=group,fill=type,alpha=background))+geom_point(cex=2,shape=1,stroke=1)+
  theme_bw()+theme(strip.background=element_blank())+scale_color_manual(drop=FALSE,values=group.colors,name="group")+
  guides(fill=guide_legend(override.aes=list(colour=type.colors,pch=0)))

所以我的问题是如何让background.colors 出现在“背景”下的图例中,而不是当前出现在那里的默认选择的灰度颜色。

【问题讨论】:

  • 我是否正确理解您想要一个分组的颜色图例?因为如果你只是想要第三个图例,你可以使用宽度或 alpha。
  • 不确定什么是分组图例。我想要的只是让 df$background 的级别与 background.colors 和标题“背景”出现在组下面的图例中。

标签: r ggplot2 legend


【解决方案1】:
ggplot(df,aes(x=x, y=y, colour=group, fill=type, alpha=background))+ 
  geom_point(cex=2, shape=1, stroke=1) + 
  theme_bw() + 
  theme(strip.background=element_blank()) +
  scale_color_manual(drop=FALSE, values=group.colors, name="group") + 
  guides(fill=guide_legend(override.aes=list(colour=type.colors,pch=0)),
         alpha=guide_legend(override.aes=list(colour=background.colors,pch=0)))

【讨论】:

    猜你喜欢
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 2021-08-07
    • 2016-03-29
    相关资源
    最近更新 更多