如何在ggplot中修改过长的因子水平名称并使其在图表中生效?
解决ggplot中因子标签不生效的问题
你当前的问题在于直接修改了整个数据框的levels,但data.frame对象本身没有levels属性,你的修改根本没作用到目标列Coding_Exp_Words上,所以绘图时还是显示原标签。
两种正确的修改方式
方式一:直接修改目标列的因子水平
针对Coding_Exp_Words列单独修改,注意原因子值在前,新标签在后,顺序要和原列的因子水平对应:
# 给Coding_Exp_Words列设置新的因子标签 levels(class_survey$Coding_Exp_Words) <- c( "None" = "None.", "Very_Little" = "Very little. I've just dipped my toe in.", "Bit" = "A bit. I've used coding in a limited capacity, such as for a small", "Some" = "Some. I've had to write code for one or two classes and am co", "Good_Deal" = "A good deal. I have several years of experience writing code." )
方式二:用forcats包的fct_recode(更直观)
tidyverse生态的forcats包提供了更清晰的因子重命名函数,新标签在前,原标签在后,无需担心顺序问题:
library(forcats) class_survey$Coding_Exp_Words <- fct_recode(class_survey$Coding_Exp_Words, None = "None.", Very_Little = "Very little. I've just dipped my toe in.", Bit = "A bit. I've used coding in a limited capacity, such as for a small", Some = "Some. I've had to write code for one or two classes and am co", Good_Deal = "A good deal. I have several years of experience writing code." )
绘图优化(可选)
如果想让标签更美观(比如把下划线换成空格),可以在ggplot中用scale_x_discrete再次调整显示文本:
ggplot(class_survey, aes(x = Coding_Exp_Words, y = Coding_Exp_Scale)) + geom_jitter() + scale_x_discrete(labels = c( "None" = "None", "Very_Little" = "Very Little", "Bit" = "A Bit", "Some" = "Some", "Good_Deal" = "Good Deal" ))
内容的提问来源于stack exchange,提问作者이우진
相关产品推荐
相关产品推荐

