Home > Software design >  ggplot geom_line: Change order of plotting
ggplot geom_line: Change order of plotting

Time:08-16

Summary:

GGplot seems to plot lineplots in an alphabetical order when aes(group = ID) is set. The line for each ID is plotted according to its (alphabetical) order. In my case this results in a quite busy plot. I'd like to have the lines of a specific group in the background. More specifically I want those lines in the background which have the most values in their group, so that they are not overlapping the lines from groups with only a few values.

Question:

How can I reorder the data in that way that the group with the most values is plotted first?

Code:

First some code to generate data to work with (not pretty but the result is good):

rm(list=ls()) 
set.seed(42)
library('ggplot2')

numOfValues <- c(20, 6, 3, 2)
System <- c(letters[1:4])
times <- c(1,2,3)
slope <- sample(1:4, size = 4)

df <- data.frame()
row <- 1
for (sys in 1:length(System)) {
  for (num in 1:numOfValues[sys]) {
    for (t in 1:length(times)) {
      # this seems stupid, but to be consistent with my data I need unique but
      # ordered ID's
      df[row, 'ID'] <- paste('P', 
                             num   if (System[sys] == 'a') {0} 
                             else if (System[sys] == 'b') {20} 
                             else if (System[sys] == 'c') {26}
                             else if (System[sys] == 'd') {28} , 
                             sep='_') 
      
      df[row, 'System'] <- System[sys]
      df[row, 'Time'] <- paste('T', times[t], sep = '')
      df[row, 'Value'] <- runif(1, 1, 10)   times[t]   slope[sys]
      row <- row   1
    }
  }
}

This is my plotting code with ggplot

p <- ggplot(data = df,
            aes(x = Time,
            y = Value, 
            group = ID,
            colour = System,
            label = ID))  
  geom_line(size = 1.5)  
  geom_point(size = 3,
             aes(shape = System))  
  theme_bw()

p

This is resulting in this graph:

unordered plot

You can see that some red lines from group a a on top and some are more in the background behind purple/green lines. It seems like that the lines get plotted in the order of the group aesthetic from ggplot, in this case by ID. This is mentioned here:

Ordered Plot

Now the lines in the largest group a are plotted first

  • Related