如何在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:
- Run your
plot.regsubsets()call withyaxt="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") - Redraw the Y-axis with your preferred number of decimal places using
axis(). For example, to show 3 decimal places:
Adjust the format string to match your needs: use# 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)%.1ffor 1 decimal place,%.4ffor 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:
- Fetch the full source code of the function by running
getS3method("plot", "regsubsets")in your console. Copy all the code into your script. - Rename the function (e.g.,
plot.regsubsets_custom) to avoid overwriting the original, then add adigits.yparameter to the function definition (set a default of 2 to match the original behavior). - Find the line where the Y-axis labels are generated (the one with
sprintf("%.2f", yval)), and replace the hardcoded2with our new parameter. We’ll build the format string dynamically usingpaste0():# 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 ... } - 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
相关产品推荐
相关产品推荐

