r - 如何使用 visreg 和 ggplot2 更改轴标签

标签 r ggplot2 plot visreg

我正在使用 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)
    

    enter image description here

    关于r - 如何使用 visreg 和 ggplot2 更改轴标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55696367/

    相关文章:

    matlab - 在一个图中绘制 4 条曲线,具有 3 个 y 轴

    python - 如何在 float 圆柱轴上旋转刻度标签?

    read.fwf 错误 "line x did not have 5 elements"- 可能是由于特殊字符

    r - 我可以告诉 dplyr 的 select() 获取索引行吗?

    使用 stringr 和 dplyr 重命名所有数据框列

    r - ggplot() 用 scale::percent_format() 缩放产生奇怪的结果

    r - 基于迭代循环变量的 ggplot2 绘图标题

    sql - 如何处理 R 连接字符串中的数据库密码?

    r - 制作智能多级直方图

    plot - QwtPlot 自定义 Axis