ggplot2:为分面网格标签添加换行且不生成额外列
ggplot2:为分面网格标签添加换行且不生成额外列
嗨,看起来你是想给ggplot分面里的长标签换行,还不想额外新增数据列对吧?我来帮你搞定这个问题~
首先先把你的数据框补全(原代码里p_m列没写完,我按照逻辑补全了内容):
# 构建数据框 phone <- c("p", "b", "t", "d", "k", "g", "ts", "dz", "tʃ", "dʒ", "f", "v", "s", "z") count <- c(1088, 211, 1260, 208, 2596, 1041, 15, 13, 1262, 51, 22, 9, 765, 8) prop <- c(0.84, 0.16, 0.86, 0.14, 0.71, 0.29, 0.53, 0.46, 0.96, 0.04, 0.71, 0.29, 0.99, 0.01) voicing <- c("unvoiced", "voiced", "unvoiced", "voiced", "unvoiced", "voiced", "unvoiced", "voiced", "unvoiced", "voiced", "unvoiced", "voiced", "unvoiced", "voiced") p_m <- c("Bilabial Plosive (N=1299)", "Bilabial Plosive (N=1299)", "Dental Plosive (N=1468)", "Dental Plosive (N=1468)", "Velar Plosive (N=3637)", "Velar Plosive (N=3637)", "Alveolar Affricate (N=28)", "Alveolar Affricate (N=28)", "Palatal Affricate (N=1313)", "Palatal Affricate (N=1313)", "Labiodental Fricative (N=31)", "Labiodental Fricative (N=31)", "Alveolar Fricative (N=773)", "Alveolar Fricative (N=773)") df <- data.frame(phone, count, prop, voicing, p_m)
假设你原本的绘图代码是类似这样的(分面展示每个发音部位的比例):
library(ggplot2) # 原始绘图,长标签会挤在一起 ggplot(df, aes(x = phone, y = prop, fill = voicing)) + geom_col() + facet_wrap(~p_m) + theme(axis.text.x = element_text(angle = 45, hjust = 1))
下面给你两种不需要新增数据列的换行方法:
方法一:手动插入换行符\n
你可以直接在现有p_m列里批量添加换行,比如在(N=前拆分文本,不用新增列:
# 批量在"(N="前插入换行 df$p_m <- gsub(" \\(N=", "\n(N=", df$p_m) # 重新绘图 ggplot(df, aes(x = phone, y = prop, fill = voicing)) + geom_col() + facet_wrap(~p_m) + theme(axis.text.x = element_text(angle = 45, hjust = 1), strip.text = element_text(size = 10)) # 可调整标签字号让换行更美观
方法二:用stringr::str_wrap自动换行
如果不想手动指定拆分位置,直接在分面函数里用str_wrap自动按字符宽度拆分,完全不用修改原始数据:
library(stringr) ggplot(df, aes(x = phone, y = prop, fill = voicing)) + geom_col() + facet_wrap(~str_wrap(p_m, width = 15)) + # 指定每行最多15个字符自动换行 theme(axis.text.x = element_text(angle = 45, hjust = 1), strip.text = element_text(size = 10))
这两种方法都不会生成额外的数据列,分面标签会自动变成多行,再也不会挤在一起啦~
备注:内容来源于stack exchange,提问作者Wangana
相关产品推荐
相关产品推荐

