【问题标题】:ggplot2: No legend with multiple geom_pointggplot2:没有具有多个 geom_point 的图例
【发布时间】:2020-05-06 16:50:37
【问题描述】:

我有一个包含多个单个 geom_point-plots 的图,我想单独指定每个图的形状和颜色。

不知何故,我真的很难获得一个合适的图例,而且我在 stackoverflow 上找不到解决方案。 我尝试在 aes 命令中使用“填充”,但如果我有两个以上的填充图,我会收到错误:

"错误:美学长度必须为1或与数据相同 (1): x, y"

这是我的情节基本结构的简化最小示例:

da <- as.character(c(1:10))
type <- c("a", "b", "c", "a", "b", "c", "a", "b", "c", "a" )
value <- c(1:10)
df <- data.frame(da, type, value)

require("ggplot2")
ggplot() + 
  geom_point(data = subset(df, type %in% c("a")), aes(x=da, y=value), shape=1, color="red",  size=5) +
  geom_point(data = subset(df, type %in% c("b")), aes(x=da, y=value), shape=2, color="darkorange", size=3) +
  geom_point(data = subset(df, type %in% c("c")), aes(x=da, y=value), shape=3, color="violet", size=3) 

如何添加带有自定义标签的图例?

谢谢! :-)

【问题讨论】:

    标签: r


    【解决方案1】:

    当您可以简单地创建一个图层并将美学映射到您的数据时,为什么还要创建单独的图层并手动创建图例(在这种情况下,只需 "type")?如果您想要特定的颜色或形状值,您可以使用诸如scale_colour_manualscale_shape_discrete 等比例来指定这些值)

    da <- as.character(c(1:10))
    type <- c("a", "b", "c", "a", "b", "c", "a", "b", "c", "a" )
    value <- c(1:10)
    df <- data.frame(da, type, value)
    
    require("ggplot2")
    #> Loading required package: ggplot2
    ggplot(df, aes(x=da, y=value, color=type, shape = type, size = type)) + 
      geom_point()
    #> Warning: Using size for a discrete variable is not advised.
    

    reprex package (v0.3.0) 于 2020-01-20 创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-15
      • 2022-11-27
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多