[英]ggplot, nested X-Axis for interaction() factor variables in bar plot
[英]R: Plot ggplot bar with "nested" variables
希望我能正確解釋。 我的數據可以在兩個層面上看到:我有四個主要類別,每個類別包含四個子類別。
在我的數據集中,我有大約 50 個觀察結果,每個觀察結果都可以分為一個主要類別和一個子類別。下圖顯示了我的類別:
1. MainCategory 1
- Subcategory 11
- Subcategory 12
- Subcategory 13
- Subcategory 14
2. MainCategory 2
- Subcategory 21
- Subcategory 22
- Subcategory 23
- Subcategory 14
etc...
一個數據行可以顯示如下:
ID Maincategory Subcategory
#1 Maincategory2 Subcategory 23
#2 Maincategory2 Subcategory 21
#3 Maincategory4 Subcategory 44
我現在的目標是使用geom_bar()
來評估我的數據行。 這應該由 4 個條形組成,每個條形代表主要類別。 在這個欄中,它應該以堆疊的方式說明子類別的計數。 所以每個條形代表主要類別的數量,並且在每個條形內 ift 不同子類別的數量
到目前為止,我的嘗試如下:(MWE 添加)
readr::read_table(
" ID Main Sub
1 Tool View Information Processing Tool
2 Ensemble View Embedded System
3 Computational View Model
4 Tool View Social Relations
6 Tool View Information Processing Tool
7 Tool View Productivity Tool
8 Nominal View Absent Technology
9 Ensemble View Embedded System
10 Nominal View Absent Technology
11 Tool View Social Relations
14 Tool View Productivity Tool
15 Proxy View Technology Perception
17 Proxy View Computer Perception
16 Computational View Algorithm"
) %>%
ggplot() +
aes(Main, Sub, fill=Main) +
geom_bar(stat="identity", position = "stack", alpha=1, width =.6,aes(fill=Main),color="white")
但是,我希望實現這樣的目標,我也在條形圖中直接寫標簽(例如 Subcategory21),就像這里所做的那樣:
正如其他人所提到的,更清楚地了解您需要什么以及要重現的代碼會有所幫助。
這是一種可能有助於促進有關您可能需要的內容的進一步討論的方法。
編輯:添加了調色板以自定義顏色。 在為您的子類別定義您想要的顏色后,在您的繪圖中使用scale_fill_manual
,如下所示。
library(tidyverse)
Palette <- c("Algorithm" = "#ff0000",
"Model" = "#ff6600",
"Embedded System" = "#99ff33",
"Absent Technology" = "#ffff00",
"Technology Perception" = "#003399",
"Information Processing" = "#cc99ff",
"Productivity Tool" = "#cc00ff",
"Social Relations" = "#cc0066")
readr::read_table(
"ID Main Sub
1 Tool View Information Processing Tool
2 Ensemble View Embedded System
3 Computational_View Model
4 Tool View Social Relations
5 Tool View Productivity Tool
6 Tool View Information Processing Tool
7 Tool View Productivity Tool
8 Nominal View Absent Technology
9 Ensemble View Embedded System
10 Nominal View Absent Technology
11 Tool View Social Relations
12 Tool View Productivity Tool
13 Tool View Productivity Tool
14 Tool View Productivity Tool
15 Proxy View Technology Perception
16 Computational_View Algorithm"
) %>%
ggplot(aes(x = Main, fill = Sub, label = str_wrap(Sub, 10))) +
geom_bar(position = "fill") +
geom_text(stat = 'count', position = position_fill(vjust = .5)) +
scale_fill_manual(name = "Sub", values = Palette)
陰謀
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.