如何使长文本适合Ggplot2方面标题 [英] How to Fit Long Text into Ggplot2 facet Titles
问题描述
我有一个关于ggplot2中的facet_wrap标签的简短问题。以下是一个简单的数据框。其中一个变量(facet变量)非常长。我想找到一种简单的方法来适应每个分面标签中的所有文字。我确定必须有某种包装文本功能或多行选项?我希望有一种不太复杂的方法,如果可能的话,并不需要任何其他包。我对R还是比较新的,希望在ggplot2中有一个简短而优雅的回答。 (不满意,满意,满意,满意,不满意,不满意,不满意 (不满意,满意,满意)
Q2 <-c(不满意,不满意,满意,不满意,不满意,满意, ,满意)
年份< -c(这是一个非常长的变量名称这是一个非常,这是另一个非常长的可变名称真的很长,这是一个短名字,短名称,这也是一个长变量名称,短名称,短名称,另一种长变量名称)
示例< -data.frame(Service,Year,Q1,Q2)
ExampleM <-melt(示例,id.vars = c(Service,Year))
ggplot(ExampleM,aes(x = variable,fill = value))+
geom_bar(position =dodge)+
facet_grid(〜Year)
常用的软件包已经具备了以下功能:use 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))
然后继续你的情节。
I have a quick question about facet_wrap labels in ggplot2. Below is a simple data frame. One of the variables (the facet variable) is very long. I want to find a simple way to fit all the text in each facet label. I'm sure there must be some kind of wrap text function or multiple line option? I'm hoping for a method that is not too complex or doesn't really require any other packages if possible.I'm still relatively new with R and hoping for a short and elegant answer within 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)
A commonly used package already has this functionality: use 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))
And then proceed with your plot.
这篇关于如何使长文本适合Ggplot2方面标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!