Home » How to Change Line Type in ggplot2

How to Change Line Type in ggplot2

by Tutor Aspire

You can use the linetype argument to change the line type in a ggplot2 plot:

ggplot(df, aes(x=x, y=y)) +
  geom_line(linetype=1)

The default value for linetype is 1 (a solid line), but you can specify any value between 0 to 6 where:

  • 0 = blank
  • 1 = solid
  • 2 = dashed
  • 3 = dotted
  • 4 = dotdash
  • 5 = longdash
  • 6 = twodash

The following examples show how to modify the linetype argument in different ggplot2 plots.

Example 1: Create Plot with Default Line Type

The following code shows how to create a line plot in ggplot2 using the default line type (solid line):

library(ggplot2)

#create data frame
df frame(x=c(1, 2, 4, 5, 8, 9),
                 y=c(5, 8, 10, 14, 13, 19))

#create line plot
ggplot(df, aes(x=x, y=y)) +
  geom_line()

Since we didn’t use the linetype argument at all, ggplot2 used the default line type of solid.

Example 2: Create Plot with Custom Line Type

The following code shows how to create a line plot in ggplot2 using dashed (linetype=2) for the line type:

library(ggplot2)

#create data frame
df frame(x=c(1, 2, 4, 5, 8, 9),
                 y=c(5, 8, 10, 14, 13, 19))

#create line plot with custom line type
ggplot(df, aes(x=x, y=y)) +
  geom_line(linetype=2)

Example 3: Create Plot with Line Type Based on Variable

The following code shows how to create a line plot in ggplot2 where the line type is based on the value of a particular variable in the data frame:

library(ggplot2)

#create data frame
df frame(x=c(1, 10, 1, 10, 1, 10),
                 y=c(5, 8, 10, 14, 13, 19),
                 group=c('A', 'A', 'B', 'B', 'C', 'C'))

#create line plot
ggplot(df, aes(x=x, y=y, group=group)) +
  geom_line(aes(linetype=group, color=group), size=1.5)

Notice that the line type and color for each line is based on the value for the group variable.

Notice that ggplot2 also automatically produces a legend on the right side of the plot to show which line corresponds to which team.

Additional Resources

The following tutorials explain how to perform other common operations in ggplot2:

How to Change Point Shape in ggplot2
How to Change Point Size in ggplot2
How to Change Line Colors in ggplot2

You may also like