Use one column for color and an other one for legend in ggplot2

僤鯓⒐⒋嵵緔 提交于 2021-01-29 07:23:19

问题


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.

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

I have tried

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

but it dosen't work !

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


回答1:


Reproducible example:

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

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




回答2:


This might help.

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

Otherwise more code might be useful.



来源:https://stackoverflow.com/questions/54065842/use-one-column-for-color-and-an-other-one-for-legend-in-ggplot2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!