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 gives for a joined scatter plot.
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 is ordering the points by x-value and joining. I need to join by time (the df is sorted by time). My actual data frame is 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, which all gave the same basic result.
>Solution :
Use geom_path(), not geom_line(). That’s what it does.
The first sentences of the shared ?geom_line/?geom_path help page is:
geom_path()connects the observations in the order in which they appear in the data.geom_line()connects them in order of the variable on the x axis.
Generally, I’d suggest consulting the help pages, at least briefly, before turning to ChatGPT.
ggplot(data=df, aes(x=x, y=y)) +
geom_path()
