ggplot2:在不同的方面使用不同的颜色 [英] ggplot2: use different colors in different facets

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

问题描述

我似乎有一个非常基本的问题,但是我无法解决,因为我几乎没有使用过ggplots2 ...我只希望左边的图使用变量color1中的颜色,而变量上的图使用right使用变量color2中的颜色.这是MWE:

I have what seems to be a very basic problem, but I cannot solve it, as I have barely used ggplots2... I just want that the plot on the left uses the colors in the variable color1 and the plot on the right uses the colors in the variable color2. This is a MWE:

library(reshape2)
library(ggplot2)

a.df <- data.frame(
  id=c("a","b","c","d","e","f","g","h"), 
  var1=c(1,2,3,4,5,6,7,8), var2=c(21,22,23,24,25,26,27,28), 
  var3=c(56,57,58,59,60,61,62,63), 
  color1=c(1,2,"NONE","NONE",1,2,2,1), 
  color2=c(1,"NONE",1,1,2,2,"NONE",2)
)

a.dfm <- melt(a.df, measure.vars=c("var2","var3"))

ggplot(a.dfm, aes(x=value, y=var1, color=color1)) + 
  geom_point(shape=1) + 
  facet_grid(. ~ variable)

非常感谢!

推荐答案

我认为处理数据最简单的方法是创建一个附加列,该列的颜色根据 variable 的值适当定义.由于 variable 可以采用两个可能的值,所以这并不难.

I think the easiest approach with your data is to create an additional column which has the color defined appropriately based on the value of variable. Since there are just two possible values that variable can take on, this isn't that hard.

a.dfm2 <- transform(a.dfm, 
                    color.use = ifelse(variable=="var2", 
                                       as.character(color1), 
                                       as.character(color2)))

ggplot(a.dfm2, aes(x=value, y=var1, color=color.use)) + 
  geom_point(shape=1) + 
  facet_grid(. ~ variable)

这篇关于ggplot2:在不同的方面使用不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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