2016-05-11 1 views
5

मेरे पास ggplot2 में facet_wrap लेबल के बारे में एक त्वरित प्रश्न है। नीचे एक साधारण डेटा फ्रेम है। चरों में से एक (पहलू परिवर्तनीय) बहुत लंबा है। मैं प्रत्येक पहलू लेबल में सभी पाठ फिट करने का एक आसान तरीका खोजना चाहता हूं। मुझे यकीन है कि किसी प्रकार का रैप टेक्स्ट फ़ंक्शन या एकाधिक लाइन विकल्प होना चाहिए? मैं ऐसी विधि की उम्मीद कर रहा हूं जो बहुत जटिल नहीं है या यदि संभव हो तो वास्तव में किसी भी अन्य पैकेज की आवश्यकता नहीं है। मैं अभी भी आर के साथ अपेक्षाकृत नया हूं और ggplot2 के भीतर एक छोटा और सुरुचिपूर्ण उत्तर की उम्मीद कर रहा हूं।Ggplot2 पहलू शीर्षक में लंबे टेक्स्ट को फ़िट करने के लिए कैसे करें

Q1<-c("Dissatisfied","Satisfied","Satisfied","Satisfied","Dissatisfied","Dissatisfied","Satisfied","Satisfied") 

Q2<-c("Dissatisfied","Dissatisfied","Satisfied","Dissatisfied","Dissatisfied","Satisfied","Satisfied","Satisfied") 



Year<-c("This is a very long variable name This is a very","This is another really long veriable name a really long","THis is a shorter name","Short name","This is also a long variable name again","Short name","Short name","Another kind of long variable name") 

Example<-data.frame(Service,Year,Q1,Q2) 

ExampleM<-melt(Example,id.vars=c("Service","Year")) 

ggplot(ExampleM, aes(x=variable, fill=value)) + 
    geom_bar(position="dodge")+ 
    facet_grid(~Year) 
+0

शायद सहायक: http://stackoverflow.com/questions/9052650/ggplot2-splitting-facet-strip-text-into-two-lines – lukeA

+0

'ggplot2 :: label_wrap_gen' – hrbrmstr

उत्तर

8

एक आमतौर पर इस्तेमाल किया पैकेज पहले से ही यह कार्यक्षमता है।

library(stringr) 
library(plyr) 
library(dplyr) 

var_width = 60 
my_plot_data <- mutate(my_plot_data, pretty_varname = str_wrap(long_varname, width = var_width)) 

और फिर अपनी साजिश के साथ आगे बढ़ें।

4

आप लाइन ब्रेक बनाने के लिए strwrap का उपयोग कर सकते हैं। यहाँ एक उदाहरण है: stringr::str_wrap() का उपयोग करें:

library(reshape2) 
library(ggplot2) 

Example<-data.frame(Year,Q1,Q2, stringsAsFactors=FALSE) 

ExampleM<-melt(Example,id.vars=c("Year")) 

# Helper function for string wrapping. 
# Default 20 character target width. 
swr = function(string, nwrap=20) { 
    paste(strwrap(string, width=nwrap), collapse="\n") 
} 
swr = Vectorize(swr) 

# Create line breaks in Year 
ExampleM$Year = swr(ExampleM$Year) 

ggplot(ExampleM, aes(x=variable, fill=value)) + 
    geom_bar(position="dodge") + 
    facet_grid(~Year) 

enter image description here

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