[英]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.