簡體   English   中英

如何使用 2 個分類變量運行 barplot?

[英]How to run barplot with 2 categorical variables?

使用以下數據,我需要構建一個直方圖,其中顏色將根據“大小”列,x 軸上的標簽將作為“模型”作為“區域”變量

df <- data.frame (model = c("A","A","A","A","A","B","B","B","B","B"),
                  size = c("med","big","small","big","small","med","big","small","big","small"),
                  sale = c(250,164,-136,125,-106,230,256,-134,114,-107),
                  area = c("med","large","narrow","large","narrow","med","large","narrow","large","narrow")
                  )

預期結果: 在此處輸入圖像描述

您可以使用facet_grid並將position_dodge2preserve = single一起使用:

ggplot(df, aes(x = area, y = sale, fill = size)) +
  geom_bar(stat = "identity", position = position_dodge2(preserve = "single")) +
  facet_grid(~ model) + 
  theme_classic() + 
  guides(fill="none")

在此處輸入圖像描述

暫無
暫無

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

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