r - R中分类变量的可视化
问题描述
通过具有以下内容dataframe
:
df = data.frame(Date=1:5,
Cat1=c(1,0,1,0,0),
Cat2=c(1,1,1,0,0),
Cat3=c(0,1,1,0,1),
Cat4=c(0,0,1,1,0))
通过使用ggplot2
,如何实现这个情节?
解决方案
您需要将数据转换为长格式,然后将 0 和 1 值转换为因子。然后您可以用 绘制geom_tile
,使用这些值作为填充颜色。
library(ggplot2)
ggplot(tidyr::pivot_longer(df, -1),
aes(x = Date, y = factor(name, levels = rev(unique(name))),
fill = as.factor(value))) +
geom_tile(color = "black") +
scale_fill_manual(values = c("white", "grey50")) +
labs(y = "") +
theme_void() +
theme(legend.position = "none",
axis.text = element_text(size = 15),
axis.title.x = element_text(size = 15),
plot.margin = margin(20, 20, 20, 20))
当然,对于最终情节的外观,您有很多选择。例如:
ggplot(tidyr::pivot_longer(df, -1),
aes(x = Date, y = factor(name, levels = rev(unique(name))),
fill = as.factor(value))) +
geom_tile(color = "black", size = 1) +
scale_fill_manual(values = c("gold", "deepskyblue4")) +
coord_equal() +
labs(y = "") +
theme_void() +
theme(legend.position = "none",
axis.text = element_text(size = 15),
axis.title.x = element_text(size = 15),
plot.margin = margin(20, 20, 20, 20))
推荐阅读
- hybris - 为什么不建议将 SAP Commerce Cloud 配方用于生产,但设置说明通常会提到使用配方?
- python - 如何解决 python 中的“ValueError: I/O operation on closed file”错误,该错误在创建新文件并写入文件时显示
- python - 迭代字典列表并从另一个列表中分配递增的值
- amazon-web-services - 如何在 Amazon Cognito 中识别唯一的移动设备 ID
- mysql - 在 Kubernetes 中为 MySQL 生产容器设置复制
- react-native - 在反应原生平面列表中滑动行剂量工作
- c# - 在 xsd 生成的数据集类的对象实例化期间出现错误
- python - Twitter 标签搜索结果 - 超过 7 天
- c# - JSON 网络与 JsonConvert
- struct - SwiftUI - 无法在 Struct 之外引用 @Published 值