我试图从以前的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)
1条答案
按热度按时间dz6r00yl1#
借用@Henrik的回答,但采取了稍微不同的路线,因为我使用两个
geom_text
层和单独的数据框来放置注解。