如何使长文本适合Ggplot2方面标题

时间:2016-05-11 22:28:33

标签: r ggplot2

我对ggplot2中的facet_wrap标签有一个简单的问题。下面是一个简单的数据框架。其中一个变量(facet变量)非常长。我想找到一种简单的方法来适应每个facet标签中的所有文本。我确定必须有某种包装文本功能或多行选项?我希望一个方法不是太复杂,或者如果可能的话也不需要任何其他包。我对R仍然相对较新,希望在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)

2 个答案:

答案 0 :(得分:13)

一个常用的包已经具有此功能:使用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))

然后继续你的情节。

答案 1 :(得分:4)

您可以使用strwrap创建换行符。这是一个例子:

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