Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot line graph with different line styles and markers

Tags:

r

ggplot2

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

like image 789
learnmorer Avatar asked Dec 08 '14 01:12

learnmorer


1 Answers

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

like image 138
jazzurro Avatar answered Oct 15 '22 16:10

jazzurro