分组条形图中的顺序一致,且缺少数据“geom_bar”

问题描述 投票:0回答:1

我正在尝试使用

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"))

enter image description here

当组中存在缺失数据时,条形的位置不一致。条被推到最左边的位置。

在这种情况下如何绘制具有一致条形位置的分组条形图?

r ggplot2 plot bar-chart visualization
1个回答
0
投票

条形的一致位置似乎需要将 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))

给予

enter image description here

xmax=3.5
中的
geom_rect
是“gear”中的因子级别数+0.5。

© www.soinside.com 2019 - 2024. All rights reserved.