2016-03-21 14 views
5

kullanarak benim faktörlerime "başlık" ekleyin ggplot2 kullanarak benim faktörler için metin/başlık eklemek istiyorum. {Reshape2} kütüphaneden veriler için Exemple içinfacet_grid

:

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

etiketlerdir Faktörler: Bayan ve Erkek.

"Seks" başlığını nasıl ekleyebilirim?

enter image description here

+0

Eh, facet_grid' 'için' etiketleyiciyi = label_both' geçebilir Original. Tam olarak istediğin şey değil (kesinlikle ... cesur değil), ama bu bir başlangıç. – alistaire

+0

Cinsiyet ile başka bir değişkeni tüm değeri kadar yapın ve bunu cinsiyet değişkeninin kendisinden önce faset'e ekleyin. – TheRimalaya

+0

laziest seçeneği 'gridExtra :: grid.arrange (last_plot(), sağ = "SEX") olacaktır. Daha kapsamlı bir alternatif, "ggplotGrob", "gtable_add_cols", "gtable_add_grob" ve "textGrob" – baptiste

cevap

4

this answer uyarlama.

Biraz daha iyi bir sürümü. Kendi genişliğini çalış.

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) 

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) 

enter image description here

+1

EVET! Teşekkür ederim @SandyMuspratt, aradığım şey buydu! – maycca

İlgili konular