在ggplot2中将一列用于颜色,将另一列用于图例 [英] Use one column for color and an other one for legend in ggplot2

查看:62
本文介绍了在ggplot2中将一列用于颜色,将另一列用于图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a data frame with 5 variable as :

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 作为图例中的标签.

I would like to use the Color column as color definition and Main as labels in the legend.

我尝试过

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

但是没用!

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

I don't find the way to do it automatically and I need a clue. Thank you.

推荐答案

可重现的示例:

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

您需要按主要"列进行排列,以免颜色被标签弄乱.
%.>%管道来自 wrapr 包.

You need to arrange by "Main" column to avoid colors being messed up with labels.
%.>% pipe is from wrapr package.

这篇关于在ggplot2中将一列用于颜色,将另一列用于图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆