Search code examples
rggplot2linelegend

Multiple Line Plots in ggplot with different colors of points and legend for line and points


I have the following data set

data = data.frame(tmu = c(0.1164966,0.01649658, 0.605479878,0.073743729, 0.21649659,0.543409994,0.1164966,0.01649658,0.605479878,
                  0.073743729,0.21649659,0.543409994,0.1164966,0.01649658,0.605479878, 0.073743729, 0.21649659,0.543409994)
                  , Method = c( rep('M1', 6), rep('M2', 6), rep('M3', 6)),
                  Value = c(1.140242, 1.016913, 2.211742,1.07824, 1.312171, 1.872045,1.131858,1.016773, 1.982265,1.077372, 1.276319,
                            1.771913,1.131858, 1.016773,1.932845, 1.077338,  1.276319, 1.756129),
                  cases = rep(c('A', 'B', 'C', 'D', 'E', 'F'),3))

I used the following code to generate the graph below.

pd <- position_dodge(width = 0.4)

ggplot(data, aes(x=tmu, y=Value, color=Method)) + 
  geom_line(size = .3, position = pd) +
  geom_point(size = 2, shape = 18, position = pd) +
  labs(fill = "") +
  theme(legend.position="bottom")

enter image description here As you can see that I have six different cases. My question is, how can I have different colors for point (cases) and also have another legend?

Thank you in advance


Solution

  • You can differentiate point and lines by using fill and color argument for example. Color for lines and fill for points while choosing a shape of points that allow fillings (such as shape = 21):

    ggplot(data, aes(x=tmu, y=Value, color = Method, group = Method)) + 
      geom_line(size = .3, position = pd) +
      geom_point(aes(fill = cases),color = "black", shape = 21,size = 2, position = pd) +
      labs(fill = "") +
      theme(legend.position="bottom")
    

    Or you can pass different color arguments into geom_line and geom_point:

    ggplot(data, aes(x=tmu, y=Value, group = Method)) + 
      geom_line(aes(color = Method), size = .3, position = pd) +
      geom_point(aes(color = cases),size = 2, shape = 18, position = pd) +
      labs(fill = "") +
      theme(legend.position="bottom")
    

    Does it answer your question ?


    NB: For some reasons, I can't upload images of the output plot... sorry for that