How to Change Line Colors in ggplot2 (With Examples)


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 default color palette 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 colors now correspond to the specific hex color codes that we chose.

Additional Resources

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

How to Rotate Axis Labels in ggplot2
How to Change Point Size in ggplot2
How to Add Text to ggplot2 Plots

Leave a Reply

Your email address will not be published. Required fields are marked *