如何在R中绘制类似Excel的(x[i],x[i+1])散点图?
Let's sort this out for you. Your goal is to plot consecutive pairs from your vector x — where each point is (x[i], x[i+1]) — and your loop-based R code isn't matching the Excel plot you already have. Let's break down why that's happening, then fix it.
Why Your Original Code Fails
The problem with your loop is that every plot(x[i], x[i+1]) call creates a brand new plot by default, even with par(new=TRUE). This means you're stacking plots on top of each other (each with their own axes) and each only shows one tiny point. The automatic axis scaling for single points also means later points might not even show up in the visible area.
The Simple, Correct Approach
Instead of looping, we can create the full set of X and Y values we need in one go, then plot them all at once. This is way more efficient and gives you full control over the plot's look.
First, let's define your vector again for clarity:
x <- c(0.542949849, 0.242292905, 0.163459552, 0.069668097, 0.042969073, 0.035829825)
Next, extract the consecutive pairs dynamically (so this works for any length vector, not just 6 elements):
- X values: All elements except the last one →
x[1:(length(x)-1)] - Y values: All elements except the first one →
x[2:length(x)]
We can assign these to variables for readability:
x_coords <- x[1:(length(x)-1)] y_coords <- x[2:length(x)]
Option 1: Scatter Plot (Matching Excel's Scatter Output)
If your Excel plot is just the individual points, use this:
plot(x_coords, y_coords, pch = 16, # Solid circle markers col = "steelblue", # Nice blue color xlab = "x[i]", ylab = "x[i+1]", main = "Consecutive Pairs from Vector x")
Option 2: Line Plot (If Excel Connects the Points)
If your Excel plot draws lines between the points in order, use type = "b" to show both points and lines, or type = "l" for just lines:
plot(x_coords, y_coords, type = "b", # Show points + connecting lines pch = 16, lwd = 2, # Thicker line for visibility col = "darkred", xlab = "x[i]", ylab = "x[i+1]", main = "Connected Consecutive Pairs from Vector x")
Quick Tips
- Skip the loop: R is designed to work with vectors, so plotting all points at once is always better than looping through individual values.
- Customize the look: Play with
pch(marker shape),col(color),lwd(line width), andtypeto match your Excel plot exactly. - Axis control: If you need to set specific axis ranges, add
xlimandylimarguments to theplot()call (e.g.,xlim = c(0, 0.6)).
内容的提问来源于stack exchange,提问作者PrettyClose

