Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda