2016-03-21 18 views
5

Chciałbym dodać tekst/tytuł dla moich czynników za pomocą ggplot2.Dodaj "tytuł" do moich czynników przy użyciu facet_grid

Dla exemple dla danych z {reshape2} biblioteki:

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

Factors etykiety są: Kobieta i mężczyzna.

Jak dodać nad nimi tytuł "seks"?

enter image description here

+0

Cóż, można przejść do etykietowania '' = label_both' do facet_grid'. Nie jest to dokładnie to, czego chcesz (na pewno nie tak ... śmiałe), ale to dopiero początek. – alistaire

+0

Utwórz kolejną zmienną z seksem jako całą jej wartość i dodaj to do aspektu przed samą zmienną płci. – TheRimalaya

+0

Najbardziej leniwą opcją byłoby 'gridExtra :: grid.arrange (last_plot(), right =" SEX ")'. Bardziej dokładną alternatywą byłoby użycie 'ggplotGrob',' gtable_add_cols', 'gtable_add_grob' oraz' textGrob' – baptiste

Odpowiedz

4

Adaptacja this answer.

Nieco lepsza wersja. Wypracuj własną szerokość.

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) 

enter image description here

+1

TAK! dziękuję @SandyMuspratt, tego właśnie szukałem! – maycca

Powiązane problemy