I want to use ggplot, preferably geom_line, to plot data points joined by a line where the data points are joined in the order they appear in the data frame. Essentially what Excel offers for a joined scatterplot.
MWE
library(ggplot2)
# Sample dataframe
df <- data.frame(
time = c(0, 1, 2, 3, 4, 5, 6, 7),
x = c(0, 1, 2, 2.5, 2, 1.5, 1, 0),
y = c(0, 2, 5, 4, 3, 1.2, 1, 0.9)
)
ggplot(data=df, aes(x=x, y=y) +
geom_line()
This consists of ordering the points by value of x and joining them. I need to join by time (the df is sorted by time). My actual data frame has about 1500 rows and the x values go up and down quite a bit (multiple loops in the data).
I tried the above and three minor variations suggested by chatGPT, and they all gave the same basic result.
geom_line() normally connects points in the order of the x variable. If you want the points to be joined according to the order of the rows (or according to time ), you must explicitly specify the grouping and use a variable that represents the sequence.
For example, if time defines the correct order:
ggplot(df, aes(x = x, y = y, group = 1)) +
geom_path()
The key difference is that geom_path() connects points in the order they appear in the dataset, while geom_line() typically sorts them by x before drawing the line. For paths, routes, or data with loops where x increases and decreases, geom_path() is usually the appropriate choice.