Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Join lines in R plot based in order in data frame

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading