2016-05-11 21 views
5

Ho una breve domanda sulle etichette facet_wrap in ggplot2. Di seguito è riportato un semplice frame di dati. Una delle variabili (la variabile facet) è molto lunga. Voglio trovare un modo semplice per adattare tutto il testo in ogni etichetta di sfaccettatura. Sono sicuro che ci deve essere una sorta di funzione di testo a capo o più opzioni di linea? Spero in un metodo che non sia troppo complesso o che non richieda realmente altri pacchetti se possibile. Sono ancora relativamente nuovo con R e spero in una risposta breve ed elegante all'interno di ggplot2.Come adattare il testo lungo in Titoli sfaccettatura 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

Forse utile: http://stackoverflow.com/questions/9052650/ggplot2-splitting-facet-strip-text-into-two-lines – lukeA

+0

'? Ggplot2 :: label_wrap_gen' – hrbrmstr

risposta

8

Un pacchetto di uso comune ha già questa funzionalità: utilizzare stringr::str_wrap().

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)) 

E quindi procedere con la trama.

4

È possibile utilizzare strwrap per creare interruzioni di riga. Ecco un esempio:

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

Problemi correlati