添加“标题"我使用facet_grid的因素 [英] Add "title" to my factors using facet_grid

查看:60
本文介绍了添加“标题"我使用facet_grid的因素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ggplot2为我的因素添加文本/标题.

例如来自{reshape2}库的数据:

  library(reshape2)库(ggplot2)ggplot(tips,aes(x = total_bill,y = tip/total_bill))+ geom_point(shape = 1)+facet_grid(性别〜.) 

因素标签为:女性和男性.

如何在其上方添加标题性别"?

解决方案

适应

I would like to add text / title for my factors using ggplot2.

For exemple for data from {reshape2} library:

library(reshape2)
library(ggplot2)
ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1) +
   facet_grid(sex ~ .)

Factors labels are: Female and Male.

How can I add above them the title "sex"?

解决方案

Adapting this answer.

Slightly better version. Work out its own width.

library(reshape2)
library(ggplot2)
library(grid)
library(gtable)

p = ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1) +
   facet_grid(sex ~ .)

# text, size, colour for added text
text = "SEX"
size = 30
col = "red"
face = "bold"

# Convert the plot to a grob
gt <- ggplotGrob(p)

# Get the positions of the right strips in the layout: t = top, l = left, ...
strip <-c(subset(gt$layout, grepl("strip-r", gt$layout$name), select = t:r))

# Text grob
text.grob = textGrob(text, rot = -90,
   gp = gpar(fontsize = size, col = col, fontface = face))

# New column to the right of current strip
# Adjusts its width to text size
width = unit(2, "grobwidth", text.grob) + unit(1, "lines")
gt <- gtable_add_cols(gt, width, max(strip$r))  

# Add text grob to new column
gt <- gtable_add_grob(gt, text.grob, 
        t = min(strip$t), l = max(strip$r) + 1, b = max(strip$b))

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

Original

library(reshape2)
library(ggplot2)
library(grid)
library(gtable)

p = ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + geom_point(shape=1) +
   facet_grid(sex ~ .)

# Convert the plot to a grob
gt <- ggplotGrob(p)

# Get the positions of the right strips in the layout: t = top, l = left, ...
strip <-c(subset(gt$layout, grepl("strip-r", gt$layout$name), select = t:r))

#  New column to the right of current strip
# Adjust the width to suit
gt <- gtable_add_cols(gt, unit(3, "lines"), max(strip$r))  

# Add text grob to new column; adjust cex (i.e., size) to suit
gt <- gtable_add_grob(gt, 
  textGrob("SEX", rot = -90, 
        gp = gpar(cex = 2, fontface = "bold", col = "RED")), 
        t = min(strip$t), l = max(strip$r) + 1, b = max(strip$b))

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

这篇关于添加“标题"我使用facet_grid的因素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆