Context: sometimes I need to change only the labels of a plot (e.g. to change the language) but I do not want to make the whole plot again as the code might be very long in some cases.
Problem: they are at least two ways to define the aesthetics labels:
- With the function
ggpot2::labs(x = ..., y = ...)and, - With the
nameargument of the scales functionsggplots::scale_*_*(name = ...)
According to the example below, it seems that, for a plot p, p + labs() can overwrite labs defined with the labs() function but not labs defined with scale_*_*(name = ...).
Question: How to avoid this behavior? Is it a bug or am I doing something wrong?
Example:
This is working as intended:
library(ggplot2)
# This is working as expected
p1 <- ggplot(data = iris, aes(x = Sepal.Width, y = Petal.Width)) +
scale_x_continuous() +
scale_y_continuous() +
labs(x = "A name",
y = "Another name")
p1
# trying to change the labs without making the plot again
p1 + labs(
x = "The new x title",
y = "The new y title"
)
While this does not:
library(ggplot2)
# This is not working
p2 <- ggplot(data = iris, aes(x = Sepal.Width, y = Petal.Width)) +
scale_x_continuous(name = "A name") +
scale_y_continuous(name = "Another name")
p2
p2 + labs(
x = "The new x title",
y = "The nex y title"
)