Update
Since ggplot2_3.0.0
您现在可以使用的版本position_dodge2
with preserve = c("total", "single")
ggplot(data,aes(x = C, y = B, label = A, fill = A)) +
geom_col(position = position_dodge2(width = 0.9, preserve = "single")) +
geom_text(position = position_dodge2(width = 0.9, preserve = "single"), angle = 90, vjust=0.25)
原答案
正如已经评论过的,你可以这样做answer:
转换A
and C
因素并使用添加看不见的变量tidyr
's complete
。自近期以来ggplot2
推荐使用的版本geom_col
代替geom_bar
在以下情况下stat = "identity"
:
data %>%
as.tibble() %>%
mutate_at(c("A", "C"), as.factor) %>%
complete(A,C) %>%
ggplot(aes(x = C, y = B, fill = A)) +
geom_col(position = "dodge")
或者使用交互项:
data %>%
ggplot(aes(x = interaction(C, A), y = B, fill = A)) +
geom_col(position = "dodge")
最后,通过将交互转换为数字,您可以根据所需的输出设置 x 轴。通过分组(group_by
)您可以计算匹配的中断。花哨的东西与{}
需要在 ggplot 参数周围直接使用变量Breaks
and C
管道内。
data %>%
mutate(gr=as.numeric(interaction(C, A))) %>%
group_by(C) %>%
mutate(Breaks=mean(gr)) %>%
{ggplot(data=.,aes(x = gr, y = B, fill = A, label = A)) +
geom_col(position = "dodge") +
geom_text(position = position_dodge(width = 0.9), angle = 90 ) +
scale_x_continuous(breaks = unique(.$Breaks),
labels = unique(.$C))}
Edit:
另一种方法是使用方面。使用space = "free_x"
允许将宽度设置为与 x 刻度的长度成比例。
library(tidyverse)
data %>%
ggplot(aes(x = A, y = B, fill = A)) +
geom_col(position = "dodge") +
facet_grid(~C, scales = "free_x", space = "free_x")
您还可以使用以下方法在底部绘制面标签switch
并删除 x 轴标签
data %>%
ggplot(aes(x = A, y = B, fill = A)) +
geom_col(position = "dodge") +
facet_grid(~C, scales = "free_x", space = "free_x", switch = "x") +
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
strip.background = element_blank())