【问题标题】:Use one column for color and an other one for legend in ggplot2在ggplot2中使用一列颜色和另一列作为图例
【发布时间】:2019-01-06 20:51:38
【问题描述】:

我有一个包含 5 个变量的数据框:

head(drop(rast.df))
  Longitude Latitude Values   Color
1 -15.10068 16.68171     32 #98d604
2 -15.08271 16.68171     32 #98d604
3 -14.99288 16.68171     32 #98d604
4 -14.97492 16.68171     32 #98d604
5 -14.95695 16.68171     32 #98d604
6 -15.11865 16.66375     32 #98d604
                                                                    Main
1 Sparse Herbaceous: dominated by herbaceous annuals (<2m) 10-60% cover.
2 Sparse Herbaceous: dominated by herbaceous annuals (<2m) 10-60% cover.
3 Sparse Herbaceous: dominated by herbaceous annuals (<2m) 10-60% cover.
4 Sparse Herbaceous: dominated by herbaceous annuals (<2m) 10-60% cover.
5 Sparse Herbaceous: dominated by herbaceous annuals (<2m) 10-60% cover.
6 Sparse Herbaceous: dominated by herbaceous annuals (<2m) 10-60% cover.

我想使用Color 列作为颜色定义,Main 作为图例中的标签。

我试过了

ggplot(rast.df)+
  geom_raster(aes(x = Longitude, y = Latitude, fill=as.factor(Values)))+
  scale_fill_manual(values=as.character(unique(rast.df$Color)), 
                       name="Experimental\nCondition",
                       breaks=unique(rast.df$Values),
                       labels=unique(rast.df$Main))

但它不起作用!

我找不到自动执行此操作的方法,我需要一个线索。 谢谢。

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    可重现的例子:

    tibble(
      Longitude = 1:5,
      Latitude = 10:14,
      Color = c('red', 'green', 'blue', 'red', 'green'),
      Main = c('A', 'C', 'B', 'A', 'C')
    ) %>%
      arrange(Main) %.>%
      ggplot(., aes(
        x = Longitude,
        y = Latitude,
        color = Main
      )) +
      geom_point() +
      scale_color_manual(values = unique(.$Color))
    

    您需要按“主”列排列以避免颜色与标签混淆。
    %.&gt;% 管道来自wrapr 包。

    【讨论】:

    • 详细说明这个答案:它之所以有效,是因为点管道运算符%.&gt;% 在用户环境中创建了一个新对象.。对象是四列小标题。这很重要,因为scale_color_manual() 无权访问传递给ggplot() 的tibble 中的变量。相反,在命令 scale_color_manual(values = unique(.$Color)) 中,scale_color_manual() 正在访问存储在点管道运算符创建的新 . 变量中的 Color 的值。
    【解决方案2】:

    这可能会有所帮助。

    ggplot( ... +
            scale_color_manual(labels = Main, values = Color) +
           ...)
    

    否则更多代码可能会有用。

    【讨论】:

    • 好像不能直接使用MainColor
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 2021-09-11
    • 2018-10-28
    • 1970-01-01
    • 2017-07-03
    相关资源
    最近更新 更多