ggplot line graph with different line styles and markers

27,174

Here is one approach. You can use two more functions to control shape and line type. scale_linetype_manual allows you to manually assign line types. Likewise, scale_shape_manual allows you to manually assigns whichever shape you want.

# Example 3: differnt line styles & different markers
ggplot(d, aes(x=X1, y=value, color=variable)) + 
geom_line(aes(linetype=variable), size=1) +
geom_point(aes(shape=variable, size=4)) +
scale_linetype_manual(values = c(1,2,1,1)) +
scale_shape_manual(values=c(0,1,2,3))

enter image description here

Share:
27,174
learnmorer
Author by

learnmorer

Updated on July 09, 2022

Comments

  • learnmorer
    learnmorer almost 2 years

    I am trying to create a line graph in ggplot2 that combines different line styles for some variable and different markers for other variables.

    Example 1 graphs each variable with a different line style, Example 2 graphs each with a different marker, and Example 3 graphs each with different lines AND markers.

    I'm trying to graph X2 and X3 with different line styles (solid, dashed) and then X4 and X5 as solid lines with different markers (circles, square, whatever).

    Is there any way to do this??

    library(ggplot2)
    library(reshape2)
    
    set.seed <- 1
    df <- data.frame(cbind(seq(1,10,1),matrix(rnorm(100,1,20), 10, 4)))
    d <- melt(df, id="X1")
    
    # Example 1: different line styles
    ggplot(d, aes(x=X1, y=value, color=variable)) + 
      geom_line(aes(linetype=variable), size=1)
    
    # Example 2: different markers for each line
    ggplot(d, aes(x=X1, y=value, color=variable)) + 
      geom_line() + geom_point(aes(shape=variable, size=4))
    
    # Example 3: differnt line styles & different markers (You see this graph below)
    ggplot(d, aes(x=X1, y=value, color=variable)) + 
      geom_line(aes(linetype=variable), size=1) +
      geom_point(aes(shape=variable, size=4))
    

    enter image description here

  • learnmorer
    learnmorer over 9 years
    Wonderful! Thanks so much for your help. I'm obviously still learning all the features of ggplot2.
  • jazzurro
    jazzurro over 9 years
    @learnmorer Pleasure. :) I am still learning ggplot2 everyday!
  • luchonacho
    luchonacho over 7 years
    I think there is an error in the geom_point line. Size should be outside the brackets: geom_point(aes(shape=variable), size=4)
  • Kevin Lee
    Kevin Lee over 7 years
    The correction provided by @luchonacho also removes the black dot '4' in the legend.