如何修改R语言investr包plotFit函数代码将散点改为柱状图?
How to Replace Scatter Points with Bar Charts in
investr::plotFit() Great question! The plotFit() function from the investr package doesn’t have a built-in parameter to swap scatter points for bar charts directly, but there’s a straightforward two-step workaround that preserves all your existing fit and confidence interval settings.
Step-by-Step Solution
The core idea is to first draw your bar chart manually, then use plotFit() to overlay the fitted line and confidence interval on top of it. Here’s how to adapt your original code:
# Assume your NLS model is stored as 'nls_model' and your raw data is in a data frame 'df' # with x variable 'x' and y variable 'y' # 1. First draw the bar chart (adjust colors/limits to match your original plot) barplot(height = df$y, # Use your raw y-values as bar heights names.arg = df$x, # Label bars with your original x-values col = "lightblue", # Customize bar color as needed ylim = c(y1, y2), # Keep your original y-axis limits xlim = c(x1, x2), # Keep your original x-axis limits xaxp = c(0, 200, 10), # Keep your original x-axis tick settings ylab = "", xlab = "", main = "") # 2. Overlay the fitted line and confidence interval with plotFit() plotFit(nls_model, interval = "confidence", level = 0.95, pch = NA, # Disable scatter points (critical to avoid overlap!) shade = TRUE, col.conf = "seagreen2", col.fit = "green", lwd.fit = 2, n = 100, add = TRUE) # Tell plotFit to draw on top of the existing bar chart
Key Parameter Explanations
add = TRUE: This tellsplotFit()to render the fit and interval on your existing bar chart instead of creating a new plot.pch = NA: This disables the default scatter point drawing, so you don’t get overlapping points on your bars.names.arg = df$x: Ensures your bar chart uses the original x-values from your data as labels, matching the axis scale from your originalplotFit()call.
Note for Continuous X-Variables
If your x-axis is continuous (not categorical), barplot() might shift bar positions slightly. For more precise alignment, use ggplot2 instead:
library(ggplot2) library(investr) # Get fitted values and confidence intervals fit_data <- predictFit(nls_model, interval = "confidence", level = 0.95, n = 100) # Plot with ggplot2 ggplot(df, aes(x = x, y = y)) + geom_col(fill = "lightblue") + geom_line(data = fit_data, aes(y = fit), color = "green", linewidth = 2) + geom_ribbon(data = fit_data, aes(ymin = lwr, ymax = upr), fill = "seagreen2", alpha = 0.3) + coord_cartesian(xlim = c(x1, x2), ylim = c(y1, y2)) + scale_x_continuous(breaks = seq(0, 200, 20)) + # Matches xaxp = c(0,200,10) labs(x = "", y = "", title = "")
内容的提问来源于stack exchange,提问作者willpkay
相关产品推荐
相关产品推荐

