通過擁有以下內容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,怎么可能實作這個情節?

uj5u.com熱心網友回復:
您需要將資料透視為長格式,然后將 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))

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/341296.html
上一篇:替換資料框中的整個字串
