4.5 C
London
Thursday, December 19, 2024
HomeTidyverse in Rggplot2 in RHow to Connect Points with Lines in ggplot2 (With Example)

How to Connect Points with Lines in ggplot2 (With Example)

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 connect points with lines in a plot in ggplot2:

library(ggplot2)

ggplot(df, aes(x=x_var, y=y_var)) +
  geom_line() +
  geom_point()

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

Example: Connect Points with Lines in ggplot2

Suppose we have the following data frame that contains the number of sales made at some store during 10 consecutive days:

#create data frame
df frame(day=1:10,
                 sales=c(3, 5, 5, 8, 12, 10, 8, 8, 5, 9))

#view data frame
df

   day sales
1    1     3
2    2     5
3    3     5
4    4     8
5    5    12
6    6    10
7    7     8
8    8     8
9    9     5
10  10     9

We can use the following code to create a plot in ggplot2 that has connected points to represent the sales made each day:

library(ggplot2)

#create plot with connected points
ggplot(df, aes(x=day, y=sales)) +
  geom_line() +
  geom_point()

connect points with lines in ggplot2

The x-axis displays the day and the y-axis displays the sales.

Also note that you can use the color, size, linetype, shape, and fill arguments to modify the appearance of both the line and the points in the plot:

library(ggplot2)

#create plot with connected points
ggplot(df, aes(x=day, y=sales)) +
  geom_line(color='grey', size=1.5, linetype='dashed') +
  geom_point(shape=21, color='black', fill='pink', size=6)

Feel free to change the values for any of these arguments to make the plot appear exactly how you would like.

Additional Resources

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

How to Plot Multiple Lines in ggplot2
How to Add an Average Line to Plot in ggplot2
How to Change Line Colors in ggplot2

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