首页 > 解决方案 > 结合两种不同美学的传说失败

问题描述

library(ggplot2)
x <- data.frame(Specimen=c("A","B","C","D"), Value=rep(0.5,4), 
                 Type=c("c1","c1","c2","c2"), Treatment=factor(rep("A", 4)),
                bar=c("hot", "cold", "cold", "cold"))

list2env(split(x, x$Type), envir = .GlobalEnv)
p1 <- ggplot() + 
  geom_bar(data=c1, aes(x = Treatment, y = Value, fill = Specimen, colour=bar), 
           stat="identity", position="fill", width=0.5) +
  scale_fill_manual("",values=c("gold", "green"))+
  scale_color_manual("",values=c("gray40","black")) +
  scale_y_continuous(expand = c(0, 0),labels = scales::percent) +
  theme(legend.position = "bottom") +
  coord_flip()    


p2 <- ggplot() + 
  geom_bar(data=c2, aes(x = Treatment, y = Value, fill = Specimen), 
           stat="identity", position="fill", col="gray40", width=0.5) +
  scale_fill_manual("",values=c("red", "blue"))+
  scale_y_continuous(expand = c(0, 0),labels = scales::percent) +
  theme(legend.position = "bottom",
        axis.text.y=element_blank()) +
  xlab("")+
  coord_flip()

library(cowplot)
plot_grid(p1,p2, nrow=1, align="v")

在此处输入图像描述

在这个例子中,我不得不关闭颜色指南,因为我无法将它与填充指南结合起来,尽管遵循了这个问题中提出的指南。关闭colp1 ( guide=F) 中的指南后,图例现在似乎以不同的方式绘制(一个带有col="gray40",另一个没有任何边框,因为 col-guide 设置为 false): 在此处输入图像描述] 1

如何结合p1中的两个图例?

标签: rggplot2

解决方案


fillcolor映射到两个不同的变量,在这种(微不足道的)情况下,“A”总是“热”而“B”总是“冷”只是偶然的。

您可以将填充和颜色都映射到Specimenor bar,但不同的变量总是会导致不同的图例。

另一种方法可能是在两个变量之间创建交互:

library(ggplot2)

ggplot() + 
  geom_col(data=c1, aes(x = Treatment, 
                        y = Value, 
                        fill = interaction(Specimen, bar, sep = '-'), 
                        color = interaction(Specimen, bar, sep = '-')), 
           position="fill", width=0.5) +
  scale_fill_manual("",values=c("gold", "green")) +
  scale_color_manual("",values=c("gray40", "black")) +
  scale_y_continuous(expand = c(0, 0),labels = scales::percent) +
  theme(legend.position = "bottom") +
  coord_flip() 

reprex 包(v0.2.0) 于 2018 年 5 月 8 日创建。


推荐阅读