You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R的plot.regsubsets中自定义Y轴小数位数?

Adjust Y-axis Decimal Places in plot.regsubsets() (R)

Quickest Fix: Redraw the Y-axis Manually

If you just need to tweak the decimal places for a single plot, you don’t have to dig into the function’s source code. Here’s a straightforward workaround:

  1. Run your plot.regsubsets() call with yaxt="n" to skip the default Y-axis rendering:
    library(leaps)
    # Example regression model
    regfit <- regsubsets(mpg ~ ., data = mtcars)
    # Generate the plot without the default Y-axis
    plot(regfit, yaxt = "n")
    
  2. Redraw the Y-axis with your preferred number of decimal places using axis(). For example, to show 3 decimal places:
    # Grab the default tick positions
    y_ticks <- axTicks(2)
    # Redraw the axis with custom formatted labels
    axis(2, at = y_ticks, labels = sprintf("%.3f", y_ticks), las = 2)
    
    Adjust the format string to match your needs: use %.1f for 1 decimal place, %.4f for 4, etc.

Permanent Fix: Modify the Function to Add a Decimal Place Parameter

Since you spotted the hardcoded %.2f in line 33 of the function, we can create a custom version of plot.regsubsets() that lets you pass a decimal place parameter directly. Here’s how:

  1. Fetch the full source code of the function by running getS3method("plot", "regsubsets") in your console. Copy all the code into your script.
  2. Rename the function (e.g., plot.regsubsets_custom) to avoid overwriting the original, then add a digits.y parameter to the function definition (set a default of 2 to match the original behavior).
  3. Find the line where the Y-axis labels are generated (the one with sprintf("%.2f", yval)), and replace the hardcoded 2 with our new parameter. We’ll build the format string dynamically using paste0():
    # Modified function snippet (use the full source you copied)
    plot.regsubsets_custom <- function (x, labels = obj$xnames, main = NULL, scale = c("bic", 
        "Cp", "adjr2", "r2"), col = gray(seq(0, 0.9, length = 10)), 
        digits.y = 2, # New parameter added here
        ...) {
        # ... rest of original code ...
        # Updated sprintf line to use digits.y
        axis(2, at = yval, labels = sprintf(paste0("%.", digits.y, "f"), yval), las = 2)
        # ... rest of original code ...
    }
    
  4. Now you can use this custom function and specify decimal places whenever you need:
    # Plot with 3 decimal places on Y-axis
    plot.regsubsets_custom(regfit, digits.y = 3)
    # Plot with 1 decimal place
    plot.regsubsets_custom(regfit, digits.y = 1)
    

内容的提问来源于stack exchange,提问作者gosuto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:05:23