如何在Plotly散点图中为轻重车辆添加线性回归斜率与置信带
How to Add Grouped Linear Regression Lines & Confidence Bands in Plotly
Got it, let's work through this! Since Plotly doesn't automatically generate grouped regression models and confidence bands like ggplot does, we'll need to manually calculate the regression outputs and confidence intervals for each vehicle group first, then plot them with add_ribbons and add_lines.
Step 1: Calculate Regression Models & Confidence Intervals
First, we'll fit separate linear models for light and heavy cars, then generate predicted values (including confidence bounds) over a sequence of x-values (log acceleration):
# Fit linear model for light cars model_light <- lm(log.mpg. ~ log.acceleration., data = cars_light) # Create a sequence of x-values to predict over (covers the range of light cars' acceleration) x_seq_light <- seq(min(cars_light$log.acceleration.), max(cars_light$log.acceleration.), length.out = 100) # Get predictions with confidence intervals pred_light <- predict(model_light, newdata = data.frame(log.acceleration. = x_seq_light), interval = "confidence") # Format into a data frame pred_light_df <- data.frame( x = x_seq_light, y_fit = pred_light[, "fit"], y_lower = pred_light[, "lwr"], y_upper = pred_light[, "upr"], wt_cat = "light" ) # Repeat for heavy cars model_heavy <- lm(log.mpg. ~ log.acceleration., data = cars_heavy) x_seq_heavy <- seq(min(cars_heavy$log.acceleration.), max(cars_heavy$log.acceleration.), length.out = 100) pred_heavy <- predict(model_heavy, newdata = data.frame(log.acceleration. = x_seq_heavy), interval = "confidence") pred_heavy_df <- data.frame( x = x_seq_heavy, y_fit = pred_heavy[, "fit"], y_lower = pred_heavy[, "lwr"], y_upper = pred_heavy[, "upr"], wt_cat = "heavy" ) # Combine both prediction datasets pred_all <- rbind(pred_light_df, pred_heavy_df)
Step 2: Plot in Plotly with Scatter Points, Regression Lines & Confidence Bands
Now we'll use plot_ly to draw the scatter points, then add the confidence bands with add_ribbons and the regression lines with add_lines:
library(plotly) plot_ly(data = cars_log, type = "scatter", x = ~log.acceleration., y = ~log.mpg., color = ~factor(wt_cat), colors = c("#8bc34a", "#ff5722"), marker = list(size = 10, opacity = 0.6), name = ~wt_cat, mode = "markers") %>% # Add confidence bands (semi-transparent ribbons) add_ribbons(data = pred_all, x = ~x, ymin = ~y_lower, ymax = ~y_upper, color = ~factor(wt_cat), colors = c("#8bc34a", "#ff5722"), opacity = 0.2, showlegend = FALSE) %>% # Add regression lines add_lines(data = pred_all, x = ~x, y = ~y_fit, color = ~factor(wt_cat), colors = c("#8bc34a", "#ff5722"), name = ~paste(wt_cat, "trend line"), mode = "lines") %>% layout(title = "Heavy vs Light Cars: Log Acceleration vs Log MPG with Regression & Confidence Bands", xaxis = list(title = "Log Acceleration"), yaxis = list(title = "Log MPG"))
Key Notes:
- Manual Model Fitting: Unlike ggplot, Plotly doesn't handle grouped model fitting automatically—so we have to fit one model per vehicle category and generate predictions explicitly.
add_ribbonsUsage: This function requires explicitx,ymin, andymaxvalues (our confidence bounds) to draw the shaded bands. We setopacity = 0.2so the bands don't obscure the scatter points.- Consistent Coloring: We use the same color palette for points, bands, and lines to keep the visualization cohesive.
内容的提问来源于stack exchange,提问作者Aida Haliti
相关产品推荐
相关产品推荐

