2016-05-11 6 views
5

ggplot2のfacet_wrapラベルについて簡単に質問します。以下は単純なデータフレームです。変数の1つ(ファセット変数)は非常に長くなります。私は各ファセットラベルにすべてのテキストを収める簡単な方法を探したい。私はある種のラップテキスト機能または複数の行オプションが必要であると確信していますか?私はまだ複雑ではない、あるいは可能なら他のパッケージを本当に必要としないメソッドを期待しています。私はまだRで新しく、ggplot2内で短くてエレガントな答えを期待しています。Ggplot2ファセットタイトルに長いテキストを合わせるには

+0

おそらく参考になる:http://stackoverflow.com/questions/9052650/ggplot2-splitting-facet-strip-text-into-two-lines – lukeA

+0

'?ggplot2 :: label_wrap_gen' – hrbrmstr

答えて

8

A一般的に使用されるパッケージは、すでにこの機能を備えています。

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

関連する問題