我正在創建兩組具有相似資料的分組條形圖(一組用于 2017 年,一組用于 2018 年)。當我創建這些圖時,我看到一個組沒有出現在 2017 年(第 1 組),但出現在 2018 年。這很好,因為 2017 年沒有該組的資料。但是,我想不出一種方法來強制傳說來認識這個失蹤的群體。此外,我看到由于 2017 年缺少該組,因此配色方案發生了變化。無論資料中是否存在特定組,我都希望圖例是統一的。所以在這種情況下,我希望圖例顯示第 1、2 和 3 組,即使它們不在兩個資料集中。另外,我注意到當一組人丟失時,欄會變粗以容納額外的空間。即使缺少某些組,有沒有辦法保持條形寬度一致?

這是構建資料集以及創建我到目前為止所做的圖的代碼:
library(dplyr)
library(ggplot2)
#### 2017 Data ###
Year <- rep(2017, 21)
Month <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Oct", "Dec", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
Group <- c(rep(2,9), rep(3,12))
Count <- c(5,1,4,3,1,1,2,5,2,14,17,8,17,10,12,10,14,16,9,9,6)
dta <- as.data.frame(cbind(Year, Month, Group, Count))
dta$Year <- as.numeric(dta$Year)
dta$Month <- as.factor(dta$Month)
dta$Group <- as.factor(dta$Group)
dta$Count <- as.numeric(dta$Count)
tmp <- dta %>%
mutate(Month = factor(Month, levels = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")))
### 2017 Plot ###
ggplot(tmp, aes(x = Month, y = Count, fill = Group))
geom_bar(stat = "identity", width = .7, position = position_dodge())
geom_text(aes(label = Count), position = position_dodge(.9), vjust = "bottom")
ggtitle("2017")
guides(fill = guide_legend(title = "Group:"))
scale_fill_brewer(palette = "Pastel1")
ylim(0, max(tmp$Count) 5)
### 2018 Data ###
Year <- rep(2020, 24)
Month <- c("May", "Aug", "Feb", "Mar", "Apr", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
Group <- c(rep(1,2), rep(2, 10), rep(3, 12))
Count <- c(1,1,2,4,1,5,4,2,2,1,3,3,38,17,6,12,27,18,18,7,6,18,15,10)
dta <- as.data.frame(cbind(Year, Month, Group, Count))
dta$Year <- as.numeric(dta$Year)
dta$Month <- as.factor(dta$Month)
dta$Group <- as.factor(dta$Group)
dta$Count <- as.numeric(dta$Count)
tmp <- dta %>%
mutate(Month = factor(Month, levels = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")))
### 2018 Plot ###
ggplot(tmp, aes(x = Month, y = Count, fill = Group))
geom_bar(stat = "identity", width = .7, position = position_dodge())
geom_text(aes(label = Count), position = position_dodge(.9), vjust = "bottom")
ggtitle("2018")
guides(fill = guide_legend(title = "Group:"))
scale_fill_brewer(palette = "Pastel1")
ylim(0, max(tmp$Count) 5)
uj5u.com熱心網友回復:
對于您的 2017 年圖,您需要確保它Group是一個因子并包含所有因子水平。您還需要設定drop = FALSE. scale_fill_brewer為了防止資料點中缺少組時條形變寬,請在preserve = "single"內部設定position_dodge()
ggplot(tmp, aes(x = Month, y = Count,
fill = factor(Group, levels = 1:3)))
geom_bar(stat = "identity", width = .7,
position = position_dodge(preserve = "single"))
geom_text(aes(label = Count),
position = position_dodge(.9), vjust = "bottom")
ggtitle("2017")
guides(fill = guide_legend(title = "Group:"))
scale_fill_brewer(palette = "Pastel1", drop = FALSE)
ylim(0, max(tmp$Count) 5)

您可以使用 2018 集運行相同的代碼(更改 除外ggtitle),您將獲得:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/443263.html
下一篇:更改GGDAG中特定節點的顏色
