3 回答

TA貢獻1789條經驗 獲得超8個贊
最簡單的方法是補充數據集,以便每個組合都存在,即使它具有NA其值。舉一個更簡單的例子(因為你的有很多不需要的功能):
dat <- data.frame(a=rep(LETTERS[1:3],3),
b=rep(letters[1:3],each=3),
v=1:9)[-2,]
ggplot(dat, aes(x=a, y=v, colour=b)) +
geom_bar(aes(fill=b), stat="identity", position="dodge")
這顯示了您要避免的行為:在組“B”中,沒有組“a”,因此條形更寬。補充dat用的所有組合一個數據幀a,并b:
dat.all <- rbind(dat, cbind(expand.grid(a=levels(dat$a), b=levels(dat$b)), v=NA))
ggplot(dat.all, aes(x=a, y=v, colour=b)) +
geom_bar(aes(fill=b), stat="identity", position="dodge")

TA貢獻1871條經驗 獲得超13個贊
ggplot2 3.0.0中引入的一些新選項position_dodge()和新選項可以提供幫助。position_dodge2()
您可以使用preserve = "single"in position_dodge()來將寬度基于單個元素,因此所有條形的寬度將相同。
ggplot(data = d, aes(x = Month, y = Quota, color = "Quota")) +
geom_line(size = 1) +
geom_col(data = d[c(-1:-5),], aes(y = Sepal.Width, fill = Species),
position = position_dodge(preserve = "single") ) +
scale_fill_manual(values = colours)
使用position_dodge2()事物居中的方式進行更改,將每組條形圖集中在每個x軸位置。它有一些padding內置,所以padding = 0用來刪除。
ggplot(data = d, aes(x = Month, y = Quota, color = "Quota")) +
geom_line(size = 1) +
geom_col(data = d[c(-1:-5),], aes(y = Sepal.Width, fill = Species),
position = position_dodge2(preserve = "single", padding = 0) ) +
scale_fill_manual(values = colours)

TA貢獻1982條經驗 獲得超2個贊
我有同樣的問題,但正在尋找一個適用于pipe(%>%)的解決方案。使用tidyr::spread和tidyr::gather來自tidyverse訣竅。我使用與@Brian Diggs相同的數據,但是當轉換為寬時,大寫變量名稱不會以雙變量名結尾:
library(tidyverse)
dat <- data.frame(A = rep(LETTERS[1:3], 3),
B = rep(letters[1:3], each = 3),
V = 1:9)[-2, ]
dat %>%
spread(key = B, value = V, fill = NA) %>% # turn data to wide, using fill = NA to generate missing values
gather(key = B, value = V, -A) %>% # go back to long, with the missings
ggplot(aes(x = A, y = V, fill = B)) +
geom_col(position = position_dodge())
編輯:
實際上,與管道結合的問題實際上有一個更簡單的解決方案。使用tidyr::complete在一行中給出相同的結果:
dat %>%
complete(A, B) %>%
ggplot(aes(x = A, y = V, fill = B)) +
geom_col(position = position_dodge())
- 3 回答
- 0 關注
- 794 瀏覽
添加回答
舉報