使用边距
来自ggplot2版本2.1.0:In
theme
,在
strip_text
元素(请参见
here
).
library(ggplot2)
library(gcookbook) # For the data set
p = ggplot(cabbage_exp, aes(x=Cultivar, y=Weight)) + geom_bar(stat="identity") +
facet_grid(. ~ Date) +
theme(strip.text = element_text(face="bold", size=9),
strip.background = element_rect(fill="lightblue", colour="black",size=1))
p +
theme(strip.text.x = element_text(margin = margin(.1, 0, .1, 0, "cm")))
原始答案更新为ggplot2 v2.2.0
您的facet_grid图表
这将减小条带的高度(如果需要,可以一直减小到零高度)。需要为一条带材和三条线材设置高度。这将适用于特定的facet_grid示例。
library(ggplot2)
library(grid)
library(gtable)
library(gcookbook)
p = ggplot(cabbage_exp, aes(x=Cultivar, y=Weight)) + geom_bar(stat="identity") +
facet_grid(. ~ Date) +
theme(strip.text = element_text(face="bold", size=9),
strip.background = element_rect(fill="lightblue", colour="black",size=1))
g = ggplotGrob(p)
g$heights[6] = unit(0.4, "cm")
for(i in 13:15) g$grobs[[i]]$heights = unit(1, "npc")
grid.newpage()
grid.draw(g)
您的Facet_wrap图表
这页下面有三条。因此,有三个带材高度需要更改,三个线材高度也需要更改。
以下内容将用于您的特定facet_wrap示例。
p = ggplot(cabbage_exp, aes(x=Cultivar, y=Weight)) + geom_bar(stat="identity") +
facet_wrap(~ Date,ncol = 1) +
theme(strip.text = element_text(face="bold", size=9),
strip.background = element_rect(fill="lightblue", colour="black",size=1))
g = ggplotGrob(p)
for(i in c(6,11,16)) g$heights[[i]] = unit(0.4,"cm")
for(i in c(17,18,19)) g$grobs[[i]]$heights <- unit(1, "npc")
grid.newpage()
grid.draw(g)
如何找到相关的高度和长度?
g$heights
返回高度向量。1空高度是绘图面板。带材高度为之前的一个,即6、11、16。
g$layout
返回最后一列中包含grob名称的数据帧。需要改变身高的人是那些名字以“strip”开头的人。它们在第17、18、19行。
概括一下
p = ggplot(cabbage_exp, aes(x=Cultivar, y=Weight)) + geom_bar(stat="identity") +
facet_wrap(~ Date,ncol = 1) +
theme(strip.text = element_text(face="bold", size=9),
strip.background = element_rect(fill="lightblue", colour="black",size=1))
g = ggplotGrob(p)
pos = c(subset(g$layout, grepl("panel", g$layout$name), select = t))
for(i in pos) g$heights[i-1] = unit(0.4,"cm")
grobs = which(grepl("strip", g$layout$name))
for(i in grobs) g$grobs[[i]]$heights <- unit(1, "npc")
grid.newpage()
grid.draw(g)
每行多个面板
几乎相同的代码可以使用,即使标题和图例位于顶部。计算中有变化
pos
,但即使没有更改,代码也会运行。
library(ggplot2)
library(grid)
df = data.frame(x= rnorm(100), y = rnorm(100), z = sample(1:12, 100, T), col = sample(c("a","b"), 100, T))
p = ggplot(df, aes(x = x, y = y, colour = col)) +
geom_point() +
labs(title = "Made-up data") +
facet_wrap(~ z, nrow = 4) +
theme(legend.position = "top")
g = ggplotGrob(p)
pos = c(unique(subset(g$layout, grepl("panel", g$layout$name), select = t)))
for(i in pos) g$heights[i-1] = unit(0.2, "cm")
grobs = which(grepl("strip", g$layout$name))
for(i in grobs) g$grobs[[i]]$heights <- unit(1, "npc")
grid.newpage()
grid.draw(g)