4

I use ggeffects::ggemmeans() to get predictions for a model. The output of ggemmeans() is of class "ggeffects", and there's a plot() method for quickly visualizing the prediction. Although the resulted visualization is a ggplot object, I can't customize the labels of the x axis ticks.

Example

library(emmeans) library(ggeffects) #> Warning: package 'ggeffects' was built under R version 4.0.4 library(ggplot2) my_model <- lm(mpg ~ factor(am), mtcars) my_ggemmeans <- ggemmeans(my_model, terms = "am") p <- plot(my_ggemmeans) p 

Created on 2021-04-28 by the reprex package (v0.3.0)

Problem

I want to edit the labels of x axis ticks to replace 1 and 0 with "manual" and "automatic"
Although p is a ggplot object:

> is.ggplot(p) [1] TRUE 

I can't use scale_x_discrete(). For example:

p + scale_x_discrete(labels = c("manual", "automatic")) 

Returns the following warning:

Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.

and the undesired plot:

enter image description here

What happened to the x axis tick labels?

Bottom line: how can I operate on p to replace the x axis tick labels?


EDIT


@Ronak's answer below suggests to rely on scale_x_continuous() and supply both breaks and labels arguments. However, this solution lacks "specificity". We can't pass a named vector to labels argument in scale_x_continuous() the way we can with scale_x_discrete() (see reference). This means that the code

p + scale_x_continuous(breaks = c(0, 1), labels = c(`1` = "number one", `0` = "number zero")) 

Gives mismatched labels: enter image description here

1 Answer 1

4

Use scale_x_continuous :

p + scale_x_continuous(breaks = c(0, 1), labels = c("manual", "automatic")) 

enter image description here

It still gives the message that it is replacing the previous scale with the new one.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! Interestingly, I can't rename properly using a named vector. If I do p + scale_x_continuous(breaks = c(0, 1), labels = c(`1` = "number one", `0` = "number zero")) I get the labels by the simple order inside c(), rather than by the names.
I don't think labels supports named vectors like that. I don't seem them mentioned in ?scale_x_continuous.
@TJMahr, the thing is that scale_x_**discrete**() does support a named vector for labels argument... also see here
I'm accepting this answer because it answers the main question in the post. I'll post a separate question regarding the labels argument.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.