2016-03-21 10 views
5

का उपयोग करके मेरे कारकों में "शीर्षक" जोड़ें ggplot2 का उपयोग करके मैं अपने कारकों के लिए टेक्स्ट/शीर्षक जोड़ना चाहता हूं।facet_grid

{reshape2} पुस्तकालय से डेटा के लिए उदाहरण के लिए:

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

कारक लेबल कर रहे हैं: महिला और पुरुष।

मैं उन्हें "लिंग" शीर्षक कैसे जोड़ सकता हूं?

enter image description here

+0

ठीक है, आप 'facet_grid' को' labeller = label_both' पारित कर सकते हैं। यह वही नहीं है जो आप चाहते हैं (निश्चित रूप से काफी नहीं ... बोल्ड), लेकिन यह एक शुरुआत है। – alistaire

+0

लिंग के साथ एक और वैरिएबल बनाएं और उसके वैल्यू के रूप में इसे सेक्स वैरिएबल से पहले पहलू में जोड़ें। – TheRimalaya

+0

सबसे अजीब विकल्प 'gridExtra :: grid.arrange (last_plot(), दाएं = "SEX") होगा। 'GgplotGrob',' gtable_add_cols', 'gtable_add_grob' और' textGrob' – baptiste

उत्तर

4

this answer अनुकूल।

थोड़ा बेहतर संस्करण। अपनी चौड़ाई का काम करें।

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

हाँ !! धन्यवाद @ सैंडीमुसप्रैट, यही वह था जो मैं ढूंढ रहा था! – maycca

संबंधित मुद्दे