刻面时如何在图下显示条形标签? [英] How to display strip labels below the plot when faceting?
本文介绍了刻面时如何在图下显示条形标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
看起来这些条总是在由 ggplot2 创建的情节之上。
例如:
库(ggplot2)
qplot(hwy,cty,data = mpg)+ facet_grid(。〜制造商)
在上方显示汽车信息。它们可以显示在底部吗?
使用
ggplot2 版本2.1.0,请考虑使用 switch ='x'
。详情请参阅?facet_grid
。 ,移动条带很容易。 (或者请参阅此处了解其他版本 - 交换x轴和strip) library(ggplot2)
library(gtable)
library(grid )
p < - ggplot(mpg,aes(hwy,cty))+ geom_point()+ facet_grid(。〜制造商)+
主题(strip.text.x = element_text = 90,vjust = 1),
strip.background = element_rect(fill = NA))
#将图转换为grob
gt< - ggplotGrob(p)
#获取布局中面板的位置:t = top,l = left,...
面板< -c(子集(gt $ layout,grepl(panel ,gt $ layout $ name),select = t:r))
#在x轴刻度标记下方添加一行,
#与条带$ b相同$ b gt = gtable_add_rows(gt,gt $ height [min(panels $ t)-1],max(panels $ b)+ 2)
#获取strip grob
stripGrob = gtable_filter(gt,strip-t)
#将grob插入新行
gt = gtable_add_grob(gt,stripGrob,t = max(面板$ b)+ 3,l = min(面板$ l),r = max(面板$ r))
#删除旧条带
gt = gt [ - (min(panels $ t)-1),]
grid.newpage()
grid.draw(gt)
It seems that the strips are always above the plot created by ggplot2. Can they be moved below the plot?
For example:
library(ggplot2)
qplot(hwy, cty, data = mpg) + facet_grid( . ~ manufacturer)
displays the car information on top. Can they be displayed be at the bottom?
解决方案
Update: Using ggplot2
version 2.1.0, consider using switch = 'x'
. See ?facet_grid
for details.
Using gtable
functions, it is easy to move the strip. (Or see here for anther version - swapping x-axis and strip)
library(ggplot2)
library(gtable)
library(grid)
p <- ggplot(mpg, aes(hwy, cty)) + geom_point() + facet_grid( . ~ manufacturer) +
theme(strip.text.x = element_text(angle = 90, vjust = 1),
strip.background = element_rect(fill = NA))
# Convert the plot to a grob
gt <- ggplotGrob(p)
# Get the positions of the panels in the layout: t = top, l = left, ...
panels <-c(subset(gt$layout, grepl("panel", gt$layout$name), select = t:r))
# Add a row below the x-axis tick mark labels,
# the same height as the strip
gt = gtable_add_rows(gt, gt$height[min(panels$t)-1], max(panels$b) + 2)
# Get the strip grob
stripGrob = gtable_filter(gt, "strip-t")
# Insert the strip grob into the new row
gt = gtable_add_grob(gt, stripGrob, t = max(panels$b) + 3, l = min(panels$l), r = max(panels$r))
# remove the old strip
gt = gt[-(min(panels$t)-1), ]
grid.newpage()
grid.draw(gt)
这篇关于刻面时如何在图下显示条形标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文