18.5 C
London
Saturday, July 19, 2025
HomeTidyverse in Rggplot2 in RHow to Change Line Colors in ggplot2 (With Examples)

How to Change Line Colors in ggplot2 (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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 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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories