ggplot组由一个分类变量和第二个颜色组成 [英] ggplot group by one categorical variable and color by a second one

查看:529
本文介绍了ggplot组由一个分类变量和第二个颜色组成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想用ggplot在R中创建下面显示的第一个图,但是两个对象都在同一个图上(没有方面包装)。



考虑一个模仿我的数据结构的简单例子:

  library (重塑2)
库(ggplot2)
x < - seq(1,5,长度= 100)
y < - replicate(10,sin(2 * pi * x)+ rnorm (10,sin(2 * pi * x)+ r norm(100,5,0.3),list)$ b $< - > - 熔体(y)
z < - 熔体(z)
df < - 数据帧(x = y $ Var1,rep = y $ Var2,y = y $值,z = z $值)
dat< - melt(df,id = c(x,rep))

我可以将它与

  ggplot(dat)+ geom_line(aes(x,value,group =颜色=变量),
alpha = 0.3)+ facet_wrap(〜变量)

并得到



,特别是 ?guide_legend

例如

  ggplot(dat)+ geom_line( aes(x,value,group = interaction(rep,variable),color = variable),
alpha = 0.3)+
scale_colour_discrete(guide = guide_legend(override.aes = list(alpha = 1)) )


Basically I'd like to create the first plot shown below in R using ggplot, but with both objects on the same graph (no facet wrapping).

Consider a minimal example that mimics my data structure:

library(reshape2)
library(ggplot2)
x <- seq(1, 5, length = 100)
y <- replicate(10, sin(2 * pi * x) + rnorm(100, 0, 0.3), "list")
z <- replicate(10, sin(2 * pi * x) + rnorm(100, 5, 0.3), "list")
y <- melt(y)
z <- melt(z)
df <- data.frame(x = y$Var1, rep = y$Var2, y = y$value, z = z$value)
dat <- melt(df, id = c("x", "rep"))

I can plot it with

ggplot(dat) + geom_line(aes(x, value, group = rep, color = variable), 
    alpha = 0.3) + facet_wrap(~variable)

And get

http://carlboettiger.info/assets/figures/2012-12-18-NA-unnamed-chunk-2.png

But if I try dropping the facet wrapping, I thought it should group by color and variable, but instead the data are not broken out correctly, resulting in nonsense:

http://carlboettiger.info/assets/figures/2012-12-18-NA-unnamed-chunk-3.png

解决方案

The problem is that the group aesthetic overrides the standard grouping protocols - it isn't included in the interaction of all discrete variables in the plot described in ?group.

So, to get your plot to work without faceting you would need to manually specify the interaction

ggplot(dat) + geom_line(aes(x, value, group = interaction(rep,variable), color = variable), alpha = 0.3) 

To override the alpha value in the aesthetic, use guide_legend(override.aes = ...)). This information can be found following the links in ?guides and specifically ?guide_legend

eg

ggplot(dat) + geom_line(aes(x, value, group = interaction(rep,variable), color = variable), 
                           alpha = 0.3) + 
  scale_colour_discrete(guide = guide_legend(override.aes = list(alpha = 1)))

这篇关于ggplot组由一个分类变量和第二个颜色组成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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