Sarah Lou
Sarah Lou

Reputation: 31

Vertical line (offset) to separate factor groups in a plot

I need help in producing a vertical line that can separate my character groups in a geom_point graph using ggplot. A simplified example is below. Ultimately, I want to produce a line that sits evenly between the locations of points on the plot to show that there are different subspecies in the following locations.

I have been able to produce vertical lines that lie directly on the identified locations on the x axis with code below, but I want them offset out in the free space between the points, not directly on top of the existing points. So for this example the first line would be halfway between W Norway and Sweden and the second line halfway between Sweden and Finland. I am including a third variable in my sample dataframe that is the actual thing I want to represent with my line, because I am guessing there may be a way to use the subspecies variable to identify the split between the groups. I also included a reordering of my sample data using scale_x_discrete because my actual dataset was getting plotted alphabetically and not according to subspecies like I want, requiring this reordering.

data <- data.frame(location = c("S Norway", "Sweden", "Finland", "W Norway"), mean = c(110, 112, 111, 110), subspecies = c("hybrid", "alpina", "schinzi", "hybrid"))

ggplot(data = data, aes(x = location, y = mean))+ geom_point()+

scale_x_discrete(limits = c("S Norway", "W Norway", "Sweden", "Finland"))+

geom_vline(xintercept = c("W Norway", "Sweden"))

Thank you so much!

Upvotes: 1

Views: 146

Answers (1)

Carl
Carl

Reputation: 7540

Like this?

library(tidyverse)

data <- data.frame(
  location = c("S Norway", "Sweden", "Finland", "W Norway"),
  mean = c(110, 112, 111, 110),
  subspecies = c("hybrid", "alpina", "schinzi", "hybrid")
)

data |> 
  ggplot(aes(x = location, y = mean)) +
  geom_point() +
  scale_x_discrete(limits = c("S Norway", "W Norway", "Sweden", "Finland")) +
  geom_vline(xintercept = c(2.5, 3.5))

Created on 2024-04-06 with reprex v2.1.0

Upvotes: 0

Related Questions