R语言 使用ggplot2可将多个x轴应用于面分割图

xytpbqjk  于 2023-03-10  发布在  其他
关注(0)|答案(1)|浏览(159)

我试图从以前的stackoverflow帖子(Multi-row x-axis labels in ggplot line chart)中复制一个答案,但是,我想将其应用到多面图中。
玩具数据。

df <- data.frame(START = rep(seq(1:10),2),
                 SAMPLE = rep(c("A", "B"), each=10),
                 yaxis = runif(20, min = 1, max = 10),
                 xaxis1 = rep(c("E1", "E1", "E2", "E2", "E1", "E2", "E3", "E4", "E1", "E2"),2),
                 xaxis2 = rep(c("G1", "G1", "G1", "G1", "G2", "G2", "G2", "G2", "G3", "G3"),2))

在这里,我希望xaxis 1出现在每个刻度上,xaxis 2只出现一次--类似于上面帖子中的YEAR-QRT图。
如果没有任何注解,图看起来就是这样。

ggplot(data = df, aes(x = interaction(START,xaxis1, xaxis2), y = yaxis, 
                    group = 1, fill=yaxis)) +
geom_col(width = 1, position = "identity") +
facet_wrap(SAMPLE ~., ncol= 1, strip.position="left")

当我尝试在图的顶部添加注解代码时,我得到不等参数长度错误。

ggplot(data = df, aes(x = START, y = yaxis, 
                      group = 1, fill=yaxis)) +
  geom_col(width = 1, position = "identity") +
  annotate(geom = "text", x = seq_len(nrow(df)), y = 34,
           label = df$xaxis1, size = 4)+
  annotate(geom = "text", x = seq_len(nrow(df)), y = 32,
           label = unique(df$xaxis2), size = 6)
dz6r00yl

dz6r00yl1#

借用@Henrik的回答,但采取了稍微不同的路线,因为我使用两个geom_text层和单独的数据框来放置注解。

library(ggplot2)
library(dplyr, warn=FALSE)

axis1 <- df |> 
  distinct(START, xaxis1, SAMPLE = "B")

axis2 <- df |> 
  distinct(START, xaxis2, SAMPLE = "B") |> 
  group_by(xaxis2, SAMPLE) |> 
  summarise(START = mean(START))
#> `summarise()` has grouped output by 'xaxis2'. You can override using the
#> `.groups` argument.

ggplot(data = df, aes(x = START, y = yaxis, 
                      group = 1)) +
  geom_col(aes(fill =yaxis),width = 1, position = "identity") +
  facet_wrap(SAMPLE ~., ncol= 1, strip.position="left") +
  geom_text(data = axis1, aes(label = xaxis1), y = -2.5, size = 4) +
  geom_text(data = axis2, aes(label = xaxis2), y = -4, size = 6) +
  coord_cartesian(clip = "off") +
  theme(plot.margin = margin(5.5, 5.5, b = 55.5, 5.5, "pt"),
        axis.title.x = element_blank())

相关问题