Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
Join lines in R chart based on 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 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.

over 2 years ago · Carlos Garzón Colorado
1 answers
Answer question

0

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.

3 months ago · Ruben Alexander Serrano Porras Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!