I'm using the visreg
package with gg = TRUE
(so it'll use ggplot2
graphics) to render my fitted model plots.
It automatically uses the names of the independent variable factors as the x axis labels, but I need them to appear slightly differently and tried to change the labels text using scale_x_discrete
as can be seen here.
But when I do so, the x axis labels, the axis line and its title become blank.
I believe I'm failing to map the labels
parameter to the breaks
parameter.
I also get the message
Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.
The problem probably lies within how visreg
stores the variables (and its levels) information. When using ggplot2
alone, this information can be easily recovered from the used dataset using data$variablename
. But by creating the basic plot through visreg
this is not so straightforward.
What I've already tried:
fit$xlevels$Species
.visreg
could be ascribing integers as the levels and trying to use
breaks = c(as.factor("1","2","3"))
.How to reproduce the problem:
library(visreg)
library(ggplot2)
data(iris)
fit <- lm(Sepal.Length ~ Species, data = iris)
visreg(fit, gg = T) +
theme(axis.line = element_line(colour = "black")) +
scale_x_discrete(breaks = c("setosa", "versicolor", "virginica"),
labels = c("SETOSA", "VERSICOLOR", "VIRGINICA"))
# ----------------------- OR the equivalent:
visreg(fit, gg = T) +
theme(axis.line = element_line(colour = "black")) +
scale_x_discrete(labels = c("setosa" = "SETOSA",
"versicolor" = "VERSICOLOR", "virginica" = "VIRGINICA"))
How the x axis looks without trying to change the labels:
library(visreg)
library(ggplot2)
data(iris)
fit <- lm(Sepal.Length ~ Species, data = iris)
visreg(fit, gg = T) +
theme(axis.line = element_line(colour = "black"))
I suggest this simple solution:
library(visreg)
library(ggplot2)
data(iris)
iris$Species <- factor(iris$Species, labels=c("SETOSA", "VERSICOLOR", "VIRGINICA"))
fit <- lm(Sepal.Length ~ Species, data = iris)
visreg(fit, gg = T)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With