簡體   English   中英

R中分類變量的可視化

[英]visualization for categorical variables in 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))

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM