结合两种不同美学的传说失败了

时间:2018-05-08 12:26:54

标签: r ggplot2

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")

enter image description here

在这个例子中,我不得不关闭颜色指南,因为我无法将它与填充指南结合起来,尽管遵循了这个问题中提出的指南。 在p1(col)中关闭guide=F指南后,图例现在看起来有所不同(一个带有col="gray40",另一个没有任何边框,因为指南是设为false): enter image description here] 1

如何在p1中组合两个传说?

1 个答案:

答案 0 :(得分:1)

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

您可以将填充和颜色映射到Specimenbar,但不同的变量将始终产生不同的图例。

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

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 package(v0.2.0)创建于2018-05-08。

相关问题