How to Change Line Colors in ggplot2 (With Examples)

Changing the line color in ggplot2 plots is a simple task. You just need to use the scale_color_manual() function and pass it a vector of colors. This function allows you to specify the line color for each group in a plot. You can also use the scale_color_brewer() function to choose from a variety of color palettes and have ggplot2 automatically assign a color to each group in your plot. Additionally, you can bind the color to a variable in your data set so that the color changes dynamically with the data.


You can use the following basic syntax to specify line colors in ggplot2:

ggplot(df, aes(x=x, y=y, group=group_var, color=group_var)) + 
    geom_line() +
    scale_color_manual(values=c('color1', 'color2', 'color3'))

The following example shows how to use this syntax in practice.

Example: Change Line Colors in ggplot2

Suppose we have the following data frame in R:

#create data frame
df <- data.frame(store=c('A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'),
                 week=c(1, 2, 3, 1, 2, 3, 1, 2, 3),
                 sales=c(9, 12, 15, 7, 9, 14, 10, 16, 19))

#view data frame
df

  store week sales
1     A    1     9
2     A    2    12
3     A    3    15
4     B    1     7
5     B    2     9
6     B    3    14
7     C    1    10
8     C    2    16
9     C    3    19

Now suppose we create the following line plot in ggplot2 to visualize the total sales by week and by store:

library(ggplot2)

#create line plot
ggplot(df, aes(x=week, y=sales, group=store, color=store)) + 
    geom_line(size=2)

By default, ggplot2 uses a with red, green, and blue for the lines.

However, you can use the scale_color_manual() function to specify your own colors for the lines:

library(ggplot2)

#create line plot
ggplot(df, aes(x=week, y=sales, group=store, color=store)) + 
    geom_line(size=2) +
    scale_color_manual(values=c('orange', 'pink', 'red'))

The colors are now orange, pink, and red.

Note that you can also use hex color codes to specify the colors:

library(ggplot2)

#create line plot
ggplot(df, aes(x=week, y=sales, group=store, color=store)) + 
    geom_line(size=2) +
    scale_color_manual(values=c('#063970', '#A69943', '#7843a6'))

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

x