繁体   English   中英

如何在ggplot2中创建多个混合图例

[英]How to create multiple mixed legends in ggplot2

我在ggplot2有以下绘图(对ChickWeight数据帧进行的修改):

require(ggplot2) 
ChickWt <- data.frame(ChickWeight, Sex = rep(c("M", "F"), times = 289))  
p1 <- ggplot(ChickWt, aes(x=Time, y=weight,
colour=Diet, Group = Chick, linetype = Sex)) + geom_line()
p1

结果如下:

在此处输入图片说明

除了图例,这很好。

我希望图例有四对:

Diet 1-M(紫色,实线),Diet 1-F(紫色,破线),

Diet 2-M(绿色,实线),Diet 2-F(绿色,破线),....

等等。 假设我想将标签放在2x2的块中。 我相信我可以使用

p1 + guides(fill=guide_legend(nrow = 2, ncol = 2))

但是我很困惑的问题是,如何使四对饮食性别组合成为传奇。 任何建议将是一个很大的帮助!

您可以使用interaction功能生成DietSex所有组合,然后手动将颜色和线型设置为每种Diet-Sex组合所需的值,从而获得单个图例。

require(ggplot2)
require(dplyr)

# Add Sex column
set.seed(104)
ChickWt = ChickWeight %>% group_by(Chick) %>%
  mutate(Sex = sample(c("M","F"),1))

plot.colors = hcl(seq(15,375,length.out=5)[1:4],100,65)

ggplot(ChickWt, aes(x=Time, y=weight, 
                          colour=interaction(Diet,Sex,sep="-"), 
                          linetype = interaction(Diet,Sex,sep="-"), 
                          group=Chick)) + 
  geom_line() +
  scale_colour_manual(values=plot.colors[rep(1:4, 2)], name="Diet-Sex") +
  scale_linetype_manual(values=rep(1:2, each=4), name="Diet-Sex") +
  guides(colour=guide_legend(ncol=2))

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM