gpt4 book ai didi

r - 如何使长文本适合 Ggplot2 分面标题

转载 作者:行者123 更新时间:2023-12-04 05:11:53 41 4
gpt4 key购买 nike

我有一个关于 ggplot2 中 facet_wrap 标签的快速问题。下面是一个简单的数据框。其中一个变量(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)

最佳答案

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

然后继续你的情节。

关于r - 如何使长文本适合 Ggplot2 分面标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37174316/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com