为2种不同的颜色分配颜色并获得2种不同的图例 [英] Assign color to 2 different geoms and get 2 different legends

查看:45
本文介绍了为2种不同的颜色分配颜色并获得2种不同的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使 ggplot2 为不同的几何图形提供单独的图例,它们均使用颜色表示2个不同的变量.我想要3个图例,一个用于 z a b ,但一个&即使a& b,b似乎也被组合成一个传奇.b代表不同的变量.我还希望能够控制每个图例中的颜色.

How can I make ggplot2 give a separate legend for different geoms that both use color to represent 2 different variables. I'd want 3 legends, one for z, a, and b, but a & b seem to be combined into a singe legend even though a & b represent different variables. I'd also like to be able to control the colors in each legend.

dat <- data.frame(
    y = rnorm(200),
    x = sample(c("A", "B"), 200, TRUE),
    z = sample(100:200, 200, TRUE), 
    a = sample(c("male", "female"), 200, TRUE),
    b = factor(sample(1:2, 200, TRUE))
)

ggplot(dat, aes(y = y, x = x)) +
    geom_point(aes(color = a, size = z)) + 
    geom_boxplot(fill = NA, size=.75, aes(color=b)) +
    scale_color_manual(values = c("#F8766D", "#00BFC4", "orange", "purple"))

推荐答案

如果使用填充的绘图符号,则可以将一个因子映射为填充,将另一个因子映射为颜色,然后将它们分为两个比例,因此也可以使用图例

If you use a filled plotting symbol, you can map one factor to fill and the other to colour, which then separates them into two scales and, therefore, legends.

ggplot(dat, aes(y = y, x = x)) +
  geom_point(aes(fill = a, size = z), pch = 21) + 
  geom_boxplot(fill = NA, size=.75, aes(color=b)) +
  scale_color_manual(values = c("orange", "purple")) +
  scale_fill_manual(values = c("#F8766D", "#00BFC4"))

这篇关于为2种不同的颜色分配颜色并获得2种不同的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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