r - ggplot:在具有不同类别组合的图中使用相同的形状/颜色
问题描述
我有许多情节,其中出现了不同的类别组合。例如,情节 1 有类别 A、B、D 情节 2 有 A、C、D,情节 3 有 A、B、C、D。我怎样才能告诉 ggplot 对相同的类别使用相同的形状和颜色每个情节?
我的设置基本上是这样的:
df1 <- as.data.frame(cbind(sample(4), sample(4), c("A", "A", "B", "D")))
df2 <- as.data.frame(cbind(sample(4), sample(4), c("B", "C", "C", "D")))
df3 <- as.data.frame(cbind(sample(4), sample(4), c("A","B", "C", "D")))
df.lst <- list(df1, df2, df3)
plt.lst <- list()
for(df in df.lst){
plt <- ggplot(df, aes(x=V1, y=V2, color=V3, shape=V3)) +
geom_point()
plt.lst[[length(plt.lst)+1]] <- plt
}
grid.arrange(grobs=plt.lst)
这给了我不同形状/颜色的相同类别:(
解决方案
概述
使用@markus 的建议,df
在创建 3x1 绘图之前将所有数据框绑定到一个中(由 提供facet_wrap()
)将允许您在具有不同类别组合的绘图中看到相同的形状/颜色。
代码
# load necessary package -------
library(tidyverse)
# collapse individual data frames into one --------
# so that your data is tidy
df <-
list(df1 = data.frame(cbind(sample(4), sample(4), c("A", "A", "B", "D")))
, df2 = data.frame(cbind(sample(4), sample(4), c("B", "C", "C", "D")))
, df3 = data.frame(cbind(sample(4), sample(4), c("A","B", "C", "D")))) %>%
bind_rows(.id = "origin")
# create a 3x1 plot -------
df %>%
ggplot(aes(x = X1, y = X2, color = X3, shape = X3)) +
geom_point() +
facet_wrap(facets = vars(origin), nrow = 3, ncol = 1)
# end of script #
推荐阅读
- python - 使用来自另一个数据帧的条件填充和生成熊猫数据帧
- system - 可寻址性/地址空间之间的关系
- protocols - 试图解码 RS485 协议
- python - 尝试将函数应用于数据框返回“方法”对象不可下标
- python - 如何在 Python 的前两个打印行之间添加一行破折号?
- javascript - 通过 rest API 以 0 或 null 形式出现的值反应本机/弹簧启动
- javascript - 使用 jquery 改进 json 解码
- html - 使用本地文件为 UIWebView 确定“根目录”
- r - Azure Functions 中缺少 R 站点扩展
- sass - Bootstrap 4 内联网格或 Sass 混合和性能