0

I am fairly new to R and I have a problem with the usage of ggplot2 together with the melt function. In the specific case I am trying to create a multiline plot which represents certain time gaps and their evolution during a race.

Say the data frame is the following (DF_TimeGap)

   Lap Ath1 Ath2 Ath3 Ath4 Ath5
1    1   0    0    0   -1     1
2    2   0    0   14    0    28
3    3   0   -1    3    0    18
4    4   0    0    1    0     3
5    5   0   -8    1   -9     3
6    6   0  -22    0  -23     1
7    7   0    0    1  -19     3
8    8   0   -1   13   -2    13
9    9   0   -1    1    0    -1
10  10   0    5    7    8    10

I then melt it with

library(reshape2)
DFMelt_TimeGap = melt(DF_TimeGap, id.var="Lap")
names(DFMelt_TimeGap)[2] = "Rider"
names(DFMelt_TimeGap)[3] = "Gap"

and it looks like (I'll just report the first two for space reasons)

    Lap    Rider  Gap
1    1      Ath1   0
2    2      Ath1   0
3    3      Ath1   0
4    4      Ath1   0
5    5      Ath1   0
6    6      Ath1   0
7    7      Ath1   0
8    8      Ath1   0
9    9      Ath1   0
10  10      Ath1   0
11   1      Ath2   0
12   2      Ath2    0
13   3      Ath2   -1
14   4      Ath2    0
15   5      Ath2   -8
16   6      Ath2  -22
17   7      Ath2    0
18   8      Ath2   -1
19   9      Ath2   -1
20  10      Ath2    5
...

when I am trying to plot the multiline plot then

ggplot(DFMelt_TimeGap, aes(x = Lap, y = Gap, col= Rider, group = Rider)) +
  geom_point()+
  geom_line()+
  xlab("Lap")+ ylab("Gap (s)")

what I obtain is the following graph(forget about colour labels, I am avoiding unnecessary code) enter image description here

which would be fine if not for the fact that the ordering on the x axis is 1 10 2 3 4 5 6 7 8 9

Is anyone aware of how to fix this sort of issues? Thanks to everyone who is so keen to contribute

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
JacquesLeen
  • 109
  • 7

1 Answers1

3

In your melt process Lap gets somehow transformed to a character. My guess is that in your real data Lap contains already a character (or worse a factor). Then in your ggplot the x-axis is mapped to a character column, which uses alphabetical ordering by default.

You could verify that via str(DFMelt_TimeGap).

Best is to make sure that Lap is a numeric to start with so DF_TimeGap$Lap <- as.numeric(as.character(DF_TimeGap$Lap)) should fix it.

I used as.numeric(as.character(.)) in case your Lap was originally formatted as factor.

This will result in a numeric scale for your plot. You may like to add scale_x_continuous(breaks = 1:10) to have breaks at each Lap number.


If you want to stick to the factor/character variable. you have to manually adjust the ordering of the levels in DFMelt_TimeGap, which you could do via DFMelt_TimeGap$Lap <- factor(DFMelt_TimeGap$Lap, 1:10)

thothal
  • 16,690
  • 3
  • 36
  • 71