【问题标题】:R - geom_point - grouping to be used for legendR - geom_point - 用于图例的分组
【发布时间】:2018-08-18 06:19:30
【问题描述】:

我有两个 geom_point 命令应用于不同的数据帧,并希望有一个图例来指定它们。但是,我不确定如何将它们分组到传说中。如果您可以查看下面的简单示例并帮助我弄清楚为什么图中没有出现图例,我将不胜感激。谢谢!

df1=data.table(x1=c(-1,0,1), y1=c(-1,0,1))
df2=data.table(x2=c(-1,0,1), y2=c(-2,0,2))
ggplot()+
geom_point(data=df1, aes(x=x1, y=y1), color='red',  group=1) +
geom_point(data=df2, aes(x=x2, y=y2), color='blue', group=2) +
xlab("X Label")+ylab("Y Label") +
scale_colour_manual(name = "My Legend", 
                 values = group,
                 labels = c("database1", "database2"))

【问题讨论】:

  • ggplot 建议这样做的方式是将 bind_rows 一起放入一个单独的 data.frame 中,并用 id 列区分它们,然后将 color=id 放入 aes。这两个数据框必须保持分开是否有原因?
  • 只有当您将 aes() 映射到某物时才会创建图例。

标签: r ggplot2 grouping legend


【解决方案1】:

正如建议的那样,ggplot2 喜欢“整洁”的数据处理方式。在这种情况下,它涉及将数据与附加变量相结合以区分组:

colnames(df2) <- c("x1","y1")
df <- rbind(transform(df1, grp='red'), transform(df2, grp='blue'))

ggplot()+
geom_point(data=df, aes(x=x1, y=y1, color=grp),  group=1) +
xlab("X Label")+ylab("Y Label") +
scale_color_identity(guide="legend")

为了简单起见,我在这里使用了scale_color_identity,但在您开始使用scale_colour_manual 并重新标记它们的地方使用它并不难。

【讨论】:

    猜你喜欢
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 2022-11-27
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多