繁体   English   中英

如何将长文本适合Ggplot2刻面标题

[英]How to Fit Long Text into Ggplot2 facet Titles

我对ggplot2中的facet_wrap标签有一个快速的问题。 以下是一个简单的数据框。 变量之一(构面变量)非常长。 我想找到一种适合所有构面标签中所有文本的简单方法。 我确定必须有某种自动换行功能或多行选项? 我希望有一种不太复杂的方法,或者如果可能的话实际上不需要任何其他软件包.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)

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

然后继续您的情节。

您可以使用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)

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM