r - 结合两种不同美学的传说失败
问题描述
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")
在这个例子中,我不得不关闭颜色指南,因为我无法将它与填充指南结合起来,尽管遵循了这个问题中提出的指南。关闭col
p1 ( guide=F
) 中的指南后,图例现在似乎以不同的方式绘制(一个带有col="gray40"
,另一个没有任何边框,因为 col-guide 设置为 false):
] 1
如何结合p1中的两个图例?
解决方案
fill
并color
映射到两个不同的变量,在这种(微不足道的)情况下,“A”总是“热”而“B”总是“冷”只是偶然的。
您可以将填充和颜色都映射到Specimen
or 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 日创建。
推荐阅读
- javascript - 将带有内联/外部 javascript 的 HTML 插入到 chrome 扩展中
- spring-boot - JUnit4 -> JUnit5,服务单元测试代码不起作用
- reactjs - 为什么我父母的上下文会重新渲染不使用它的孩子?
- symfony - 记住我在转移到在数据库中保持会话后不再在 Symfony 5 中工作
- elasticsearch - Grafana 没有可视化日志
- python - model.get_weights() 与 model.trainable_variables Tensorflow
- flutter - 如何使用自定义键盘连接只读 TextField?
- java - 如何按降序而不是升序打印星号行
- java - Hibernate 更新调用在 @OneToOne 映射中生成新行
- macos - docker.bintray.io/jfrog/artifactory 7.18.6 版本运行失败