我正在使用 visreg
包装与 gg = TRUE
(所以它将使用 ggplot2
图形)来渲染我的拟合模型图。
它自动使用自变量因子的名称作为 x 轴标签,但我需要它们的显示略有不同,并尝试使用 scale_x_discrete
更改标签文本可以看出here .
但是当我这样做时,x 轴标签、轴线及其标题变为空白。
我相信我没有映射 labels
breaks
的参数范围。
我也收到消息
Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.
问题可能在于如何
visreg
存储变量(及其级别)信息。使用时 ggplot2
单独使用 data$variablename
可以很容易地从使用过的数据集中恢复这些信息。 .但是通过 visreg
创建基本图这不是那么简单。我已经尝试过的:
fit$xlevels$Species
访问变量级别. visreg
可能将整数作为级别并尝试使用breaks = c(as.factor("1","2","3"))
. 如何重现问题:
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"))
在不尝试更改标签的情况下 x 轴的外观:
library(visreg)
library(ggplot2)
data(iris)
fit <- lm(Sepal.Length ~ Species, data = iris)
visreg(fit, gg = T) +
theme(axis.line = element_line(colour = "black"))
最佳答案
我建议这个简单的解决方案:
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)
关于r - 如何使用 visreg 和 ggplot2 更改轴标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55696367/