Search code examples
rgroupinglines

Plot lines to group points


This is the data from my csv file:

Tx, Varx, Scale, Val1, Val2
A, VAR1, 5, 516, 2
A, VAR1, 10, 447.4, 5
A, VAR1, 15, 294, 8
A, VAR1, 20, 217.2, 12

A, VAR2, 5, 675.4, 4
A, VAR2, 10, 423.2, 9
A, VAR2, 15, 276, 12
A, VAR2, 20, 200, 15

B, VAR1, 5, 624, 6
B, VAR1, 10, 465.2, 13
B, VAR1, 15, 315.2, 16
B, VAR1, 20, 234.8, 18

B, VAR2, 5, 518.8, 8
B, VAR2, 10, 443, 17
B, VAR2, 15, 278.4, 20
B, VAR2, 20, 217.8, 24

I want to plot lines (not only points) to distingish between Varx and Tx values. I'm trying to plot with this code:

data_table = read.csv("PATH/file.csv",check.names=FALSE,header=T,sep=",")
data_table$NScale <- as.numeric(as.character((data_table$Scale)))
ggplot(data_table, aes(x=NScale, y=Val2, colour=Tx, shape=Varx, linetype=Varx, group=Tx)) + geom_point()

enter image description here

When I try to plot lines for joining blue triangules, red triangules, red circles, blue circles, using geom_line(), geom_path() an error message is displayed:

Error: geom_path: If you are using dotted or dashed lines, colour, size and linetype must be constant over the line

How I can create the lines grouping by shape and color? I've tried several ways, but still do not get it. What is the problem?


Solution

  • You should try to make a new "grouping" variable and separate how you do the plot for the "points" and the "line".

    I've done this here using dplyr but you could do it using base R as well:

    library(dplyr)
    
    data_table <- data_table %>% 
      rowwise() %>%
      mutate(TxVarxgroup = paste0(Tx, Varx, collapse=""))
    
    ggplot(data_table) + 
      geom_point(aes(x=NScale, y=Val2, colour=Tx, shape=Varx)) + 
      geom_line(aes(x=NScale, y=Val2, group=TxVarxgroup))
    

    enter image description here