如何操作 facet_grid 图的条形文本?

我想知道如何操纵刻面图中条形文本的大小,我的问题是 类似于 关于情节标题的问题但我特别关注的是 不是处理情节标题,而是处理方面标题中出现的文本(Strip _ h)。

例如,考虑 mpg 数据集。

    library(ggplot2)
qplot(hwy, cty, data = mpg) + facet_grid( . ~ manufacturer)

由此产生的 输出产生一些方面的标题,不适合在条。

我在想一定有办法用 grid来处理脱衣文本 还是个新手,不知道 Hadley 的书grid阑尾是怎么回事, 准确地说,是去做这件事。而且,我还担心如果我做错了,会把我洗的衣服弄坏 机器,因为我相信所有的技术都是通过原力联系在一起的:

非常感谢。

73482 次浏览

You can modify strip.text.x (or strip.text.y) using theme_text(), for instance

qplot(hwy, cty, data = mpg) +
facet_grid(. ~ manufacturer) +
opts(strip.text.x = theme_text(size = 8, colour = "red", angle = 90))

Update: for ggplot2 version > 0.9.1

qplot(hwy, cty, data = mpg) +
facet_grid(. ~ manufacturer) +
theme(strip.text.x = element_text(size = 8, colour = "red", angle = 90))

Nowadays the usage of opts and theme_text seems to be deprecated. R suggests to use theme and element_text. A solution to the answer can be found here: http://wiki.stdout.org/rcookbook/Graphs/Facets%20%28ggplot2%29/#modifying-facet-label-text

qplot(hwy, cty, data = mpg) +
facet_grid(. ~ manufacturer) +
theme(strip.text.x = element_text(size = 8, colour = "red", angle = 90))

I guess in the example of mpg changing the rotation angle and font size is fine, but in many cases you might find yourself with variables that have quite lengthy labels, and it can become a pain in the neck (literally) to try read rotated lengthy labels.

So in addition (or complement) to changing angles and sizes, I usually reformat the labels of the factors that define the facet_grid whenever they can be split in a way that makes sense.

Typically if I have a dataset$variable with strings that looks like

c("median_something", "aggregated_average_x","error","something_else")

I simply do:

reformat <– function(x,lab="\n"){ sapply(x, function(c){ paste(unlist(strsplit(as.character(c) , split="_")),collapse=lab) }) }

[perhaps there are better definitions of reformat but at least this one works fine.]

dataset$variable <- factor(dataset$variable, labels=reformat(dataset$variable, lab='\n')

And upon facetting, all labels will be very readable:

ggplot(data=dataset, aes(x,y)) + geom_point() + facet_grid(. ~ variable)