簡體   English   中英

如何增加給定的兩個堆疊條之間的空間?

[英]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

這是一個快速破解,但具有更多專業知識的同事無疑會提供更優雅的答案:

  1. Year重命名為其他名稱,並添加一個新的連續Year來表示您想要的間隙:
Data <- Data %>% rename(grp=Year) %>% mutate(Year = rep(c(1,2,4,5),each=4))
  1. 添加scale_x_continuous()指示您想要的中斷和標簽。
scale_x_continuous(breaks=c(1,2,4,5),labels = unique(Data$grp))

bar_with_space

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM