使用R Plotly绘制二次回归线:新手实操技术咨询
Hey there! Since you're already familiar with fitting the second-order polynomial models using lm(), let's put those fits to work with Plotly to create clear, interactive plots for both your variable pairs. Here's a complete, step-by-step solution tailored to your data:
Step 1: Load Required Packages & Prepare Your Data
First, make sure you have Plotly installed (run install.packages("plotly") if you haven't already), then load it along with basic data-handling tools:
# Install package if missing # install.packages("plotly") library(plotly) # Define your data and wrap it in a data frame (simplifies plotting) price <- c(995, 675, 690, 600, 612, 700, 589, 532, 448, 512, 537, 560) score <- c(89, 91, 88, 89, 91, 91, 89, 93, 83, 91, 91, 90) year <- c(2005:2016) df <- data.frame(year, score, price)
Step 2: Fit the Second-Order Polynomial Models
You mentioned you already have qfit1 working, but let's include both fits explicitly. We use poly(..., raw = TRUE) to work with intuitive raw polynomial terms instead of orthogonal ones:
# Price vs. Year quadratic fit qfit1 <- lm(price ~ poly(year, 2, raw = TRUE), data = df) # Price vs. Score quadratic fit qfit2 <- lm(price ~ poly(score, 2, raw = TRUE), data = df)
Step 3: Generate Smooth Prediction Sequences
To create a clean, smooth regression line (not just connecting original data points), we'll generate dense sequences of predictor values and use our models to predict corresponding prices:
# Smooth sequence for year (covers full range of your data) year_seq <- seq(min(df$year), max(df$year), length.out = 100) pred_year <- predict(qfit1, newdata = data.frame(year = year_seq)) # Smooth sequence for score score_seq <- seq(min(df$score), max(df$score), length.out = 100) pred_score <- predict(qfit2, newdata = data.frame(score = score_seq))
Step 4: Create Interactive Plotly Plots
We'll build two separate interactive plots, plus an option to combine them into side-by-side subplots:
Option 1: Separate Plots
First, the Price vs. Year plot:
plot_year <- plot_ly(df, x = ~year, y = ~price, type = "scatter", mode = "markers", name = "Raw Data", marker = list(color = "darkgray")) %>% add_trace(x = ~year_seq, y = ~pred_year, type = "scatter", mode = "lines", name = "Quadratic Fit", line = list(color = "#e74c3c", width = 2)) %>% layout(title = "Price vs. Year: Second-Order Polynomial Fit", xaxis = list(title = "Year"), yaxis = list(title = "Price"), showlegend = TRUE) # Display the plot plot_year
Then the Price vs. Score plot:
plot_score <- plot_ly(df, x = ~score, y = ~price, type = "scatter", mode = "markers", name = "Raw Data", marker = list(color = "darkgray")) %>% add_trace(x = ~score_seq, y = ~pred_score, type = "scatter", mode = "lines", name = "Quadratic Fit", line = list(color = "#3498db", width = 2)) %>% layout(title = "Price vs. Score: Second-Order Polynomial Fit", xaxis = list(title = "Score"), yaxis = list(title = "Price"), showlegend = TRUE) # Display the plot plot_score
Option 2: Combined Subplots
If you want to compare both fits side-by-side (or stacked), use subplot():
subplot(plot_year, plot_score, nrows = 2, shareY = TRUE) %>% layout(title = list(text = "Quadratic Polynomial Fits: Price vs. Year & Score", x = 0.5), margin = list(t = 60))
A Quick Tip
All plots are interactive—you can hover over points to see exact values, zoom, pan, and toggle the legend to show/hide raw data or the fit line. Feel free to tweak colors, line widths, or titles to match your preferences!
内容的提问来源于stack exchange,提问作者Giannis K

