完全删除 facet_敏感标签

我想去掉标签的方面完全创建一种 火花的效果,为观众的标签是无关紧要的,我能想到的最好的是:

library(MASS)
library(ggplot2)
qplot(week,y,data=bacteria,group=ID, geom=c('point','line'), xlab='', ylab='') +
facet_wrap(~ID) +
theme(strip.text.x = element_text(size=0))

那么,我是否可以完全去掉 strip.back (现在是空白的) ,以便为“火花线”留出更多的空间?

或者,是否有一个更好的方法来获得这种“ 火花”效应的大量二值时间序列像这样?

100700 次浏览

For ggplot v2.1.0 or higher, use element_blank() to remove unwanted elements:

library(MASS) # To get the data
library(ggplot2)


qplot(
week,
y,
data = bacteria,
group = ID,
geom = c('point', 'line'),
xlab = '',
ylab = ''
) +
facet_wrap(~ ID) +
theme(
strip.background = element_blank(),
strip.text.x = element_blank()
)

In this case, the element you're trying to remove is called strip.

ggplot2 figure without panel titles


Alternative using ggplot grob layout

In older versions of ggplot (before v2.1.0), the strip text occupies rows in the gtable layout.

element_blank removes the text and the background, but it does not remove the space that the row occupied.

This code removes those rows from the layout:

library(ggplot2)
library(grid)


p <- qplot(
week,
y,
data = bacteria,
group = ID,
geom = c('point', 'line'),
xlab = '',
ylab = ''
) +
facet_wrap(~ ID)


# Get the ggplot grob
gt <- ggplotGrob(p)


# Locate the tops of the plot panels
panels <- grep("panel", gt$layout$name)
top <- unique(gt$layout$t[panels])


# Remove the rows immediately above the plot panel
gt = gt[-(top-1), ]


# Draw it
grid.newpage()
grid.draw(gt)

As near as I can tell, Sandy's answer is correct but I think it's worth mentioning that there seems to be a small difference the width of a plot with no facets and the width of a plot with the facets removed.

It isn't obvious unless you're looking for it but, if you stack plots using the viewport layouts that Wickham recommends in his book, the difference becomes apparent.

I'm using ggplot2 version 1 and the commands required have changed. Instead of

ggplot() ... +
opts(strip.background = theme_blank(), strip.text.x = theme_blank())

you now use

ggplot() ... +
theme(strip.background = element_blank(), strip.text = element_blank())

For more detail see http://docs.ggplot2.org/current/theme.html

Sandy's updated answer seems good but, possibly has been rendered obsolete by updates to ggplot? From what I can tell the following code (a simplified version of Sandy's original answer) reproduces Sean's original graph without any extra space:

library(ggplot2)
library(grid)
qplot(week,y,data=bacteria,group=ID, geom=c('point','line'), xlab='', ylab='') +
facet_wrap(~ID) +
theme(strip.text.x = element_blank())

I am using ggplot 2.0.0.