Home > OS >  rename levels in ggplot because they are too long
rename levels in ggplot because they are too long

Time:09-12

I'm trying to change the factor names because they appear too long on the plot.

Codes:

levels(class_survey) <- list(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.") 

and I"m trying to make them appear in my actual plot, but I can't figure out how.

ggplot(class_survey, aes(x = Coding_Exp_Words, y = Coding_Exp_Scale))   geom_jitter()

Coding_Exp_words is the data column whose label names I'm trying to change their label names. .

CodePudding user response:

There are a variety of ways to do this.

class_survey_info <-  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.") 

(This information might as well be in a named character vector as in a list ...)

  1. Use factor() with levels set equal to your original levels and labels as your short versions (see this answer).
class_survey <- (class_survey
   |> mutate(across(Coding_Exp_Words, factor, levels = class_survey_info,
                    labels = names(class_survey_info)))
)
ggplot(...)
  1. Use forcats::recode() (mutate(across(Coding_Exp_Words, ~forcats::recode(., !!!class_survey_info) )

  2. Specify breaks and values in your x-axis scale.

ggplot(...)  
  scale_x_discrete(breaks = class_survey_info, labels = names(class_survey_info))

(haven't tested because no reproducible example).

Solutions #1 and #2 can be done either in tidyverse with regular pipes (|> or %>%), or with magrittr's assignment pipe (class_survey %<>% mutate(...)), or in base R (class_survey <- transform(class_survey, Coding_Exp_Words = factor(...)) or class_survey$Coding_Exp_Words <- factor(class_survey$Coding_Exp_Words, ...))

  •  Tags:  
  • r
  • Related