我正在尝试使用
ggplot2
绘制分组条形图,如下所示。
library(ggplot2)
data(mtcars)
mtcars$gear <- as.factor(mtcars$gear)
mtcars$carb <- as.factor(mtcars$carb)
ggplot() +
geom_bar(data = mtcars, aes(x = carb), alpha = 0.2) +
geom_bar(data = mtcars, mapping = aes(x = carb, fill = gear),
position = position_dodge(preserve = "single"))
当组中存在缺失数据时,条形的位置不一致。条被推到最左边的位置。
在这种情况下如何绘制具有一致条形位置的分组条形图?
条形的一致位置似乎需要将 x 轴映射到“gear”变量,而不是“carb”变量。但是,您已经将 x 轴映射到整个条形图中的“carb”变量。因此,你陷入了困境。
一种可能的解决方法是对整体条形使用
geom_rect
(计数后),然后在“碳水化合物”上进行分面。然后我们可以使用 x 轴的“齿轮”变量,它们将保持在固定或“一致”的位置。
library(ggplot2)
library(ddplyr)
count(mtcars, carb) |>
ggplot() +
geom_rect(aes(xmin = 0.5, xmax=3.5, ymin=0, ymax=n), alpha = 0.2) +
geom_bar(data = mtcars, mapping = aes(x = gear, fill = gear)) +
facet_grid(~carb, switch="x") +
theme(axis.text.x=element_blank(),
axis.ticks.x=element_blank()) +
labs(x="carb") +
scale_y_continuous(expand=c(0,0))
给予
xmax=3.5
中的geom_rect
是“gear”中的因子级别数+0.5。