R语言 在ggplot条形图的x轴上以特定间隔添加间隙

ztyzrc3y  于 2023-02-06  发布在  其他
关注(0)|答案(1)|浏览(259)

我这里有一个模拟数据集,我想在x轴上以特定的间隔引入更大的间隙。
我希望这些差距更大,特别是日间组之间。
在这种情况下,在前2组之后,然后在后2组之后,然后在接下来的3组之后,差距会更大,依此类推......
以下是我当前的输出:

下面是我的代码:

library("ggplot2")
library("grid")
library("dplyr")

df <- data.frame(
  day = c(rep(11, 6), rep(12, 6), rep(23, 9), rep(31, 9), rep(47, 9)),
  hz = c(rep(1, 3), rep(2, 3), rep(1, 3), rep(2, 3), rep(1, 3), rep(2, 3), rep(4, 3) , rep(1, 3), rep(2, 3), rep(4, 3), rep(1, 3), rep(2, 3), rep(4, 3)),
  ft = c(38,42,45,28,30,45,38,41,45,25,30,45,45,43,50,30,28,48,30,33,40,45,41,47,38,35,43,30,32,50,46,40,50,38,30,40,30,28,40),
  sp = c(rep(c("Ctrl", "Absrc", "Ab42"), 13))
)

se <- function(a) sd(a)/sqrt(length(a))

g1 <- ggplot(df, aes(x=interaction(hz, day), y=ft, group=desc(sp), fill=sp)) +
  geom_bar(position=position_dodge(), stat="identity") +
  geom_errorbar(aes(ymax=ft+se(ft), ymin=ft-se(ft)), position=position_dodge(0.9), width=0.5) +
  coord_cartesian(ylim=c(0, 60)) +
  annotate("text", x=c(1.5, 3.5, 6, 9, 12), y=-6, label=c("day 11", "day 12", "day 23", "day 31", "day 47")) +
  annotate("text", x=1:13, y=-3, label=c(rep(c("1 hz", "2hz"), 2), rep(c("1 hz", "2 hz", "4hz"), 3))) +
  theme_classic() + 
  theme(plot.margin=unit(c(1,1,4,1), "lines"),
        axis.title.x= element_blank(),
        axis.text.x=element_blank()) + 
  scale_fill_discrete(breaks=c("Ctrl", "Absrc", "Ab42")) + 
  scale_fill_grey() + 
  scale_y_continuous(expand=c(0,0))

g2 <- ggplot_gtable(ggplot_build(g1))
g2$layout$clip[g2$layout$name == "panel"] <- "off"
grid.draw(g2)

ggsave(file="graph.svg", plot=g2)
xxb16uws

xxb16uws1#

一种选择是使用刻面,它也允许添加日期标签,而不需要annotate黑客。如果你不想在轴上的间隙,你可以设置面板间距为零,而不是增加x比例的扩展,以增加一些面板之间的空间:

library(ggplot2)

ggplot(df, aes(x = interaction(hz, day), y = ft, group = desc(sp), fill = sp)) +
  geom_bar(position = position_dodge(), stat = "identity") +
  geom_errorbar(aes(ymax = ft + se(ft), ymin = ft - se(ft)), position = position_dodge(0.9), width = 0.5) +
  scale_x_discrete(labels = ~paste(substr(.x, 1, 1), "hz")) +
  facet_grid(.~day, switch = "x", scales = "free_x", space = "free_x",
             labeller = labeller(day = ~ paste("day", .x))) +
  coord_cartesian(ylim = c(0, 60), clip = "off") +
  theme_classic() +
  theme(
    plot.margin = unit(c(1, 1, 1, 1), "lines"),
    axis.title.x = element_blank(),
    strip.background.x = element_blank(),
    strip.placement = "outside",
    #panel.spacing.x = unit(0, "pt")
  ) +
  scale_fill_grey(breaks = c("Ctrl", "Absrc", "Ab42")) +
  scale_y_continuous(expand = c(0, 0))

相关问题