Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change axis labels using with visreg along with ggplot2

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:

  • Using the variable's levels' names as plotted by default as the breaks.
  • Trying to access the variable levels with fit$xlevels$Species.
  • Guessing 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"))
like image 903
Hohl Avatar asked Apr 15 '19 19:04

Hohl


1 Answers

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)

enter image description here

like image 71
Marco Sandri Avatar answered Sep 29 '22 12:09

Marco Sandri