[英]How to increase space between the given two stacked bars?
如何為以下代碼增加給定的兩個堆疊條之間的空間(例如,第二個和第三個堆疊條之間)? rest 空間無需更改。 非常感謝!
library(ggplot2)
rm(list = ls())
Year <- c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 4))
Category <- c(rep(c("A", "B", "C", "D"), times = 4))
Frequency <- c(168, 259, 226, 340, 216, 431, 319, 368, 423, 645, 234, 685, 166, 467, 274, 251)
Data <- data.frame(Year, Category, Frequency)
ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
geom_bar(stat = "identity",width = 0.8) +
geom_text(size = 3, position = position_stack(vjust = 0.5))
您可以使用ggplot_build
更改第三條的xmin
和第二條的xmax
。 我用 0.1 改變了它,所以你可以修改它。 這是一個可重現的示例:
library(ggplot2)
library(dplyr)
Year <- c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 4))
Category <- c(rep(c("A", "B", "C", "D"), times = 4))
Frequency <- c(168, 259, 226, 340, 216, 431, 319, 368, 423, 645, 234, 685, 166, 467, 274, 251)
Data <- data.frame(Year, Category, Frequency)
p <- ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
geom_bar(stat = "identity") +
geom_text(size = 3, position = position_stack(vjust = 0.5))
# Old plot
p
q <- ggplot_build(p)
# Here you can decide the distance between specific bars
q$data[[1]] <- q$data[[1]] %>%
mutate(xmin = ifelse(x == 3, xmin + 0.1, xmin),
xmax = ifelse(x == 2, xmax - 0.1, xmax))
q <- ggplot_gtable(q)
# New plot
plot(q)
使用reprex v2.0.2創建於 2022-08-26
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.