Ggplot: multiple lines starting at the same point

I have a dataset like this one:

df <- data.frame(Species = c("Sp A", "Other sp", "Other sp", "Other sp",
                       "Sp A", "Other sp", "Other sp"), 
           Study = c("A", "A", "A", "A", 
                     "B", "B", "B"), 
           Value = c(1, 3, 4, 5, 3, 6, 7))

      

Looks like:

> df
   Species Study Value
1     Sp A     A     1
2 Other sp     A     3
3 Other sp     A     4
4 Other sp     A     5
5     Sp A     B     3
6 Other sp     B     6
7 Other sp     B     7

      

I would like to compare values ​​of view A with values ​​of other views from the same study.
This is the plot I have now:

ggplot(df, aes(y = Value, x = Species)) + 
    geom_point(shape = 1) +
    geom_line(aes(group = Study), color = "gray50") +
    theme_bw()

      

enter image description here

I don't want vertical lines. Instead, I would like to have 5 lines starting from the bottom "Sp A" towards 3 corresponding "other sp" points from the same study (A) and 2 starting from the top "Sp A" towards 2 other points from that same study (B).

+3


source to share


2 answers


There might be a more elegant way to do this, but here's a solution that works. The trick is to change the data a bit and then use geom_segment

:

library(tidyverse)
df <- data.frame(Species = c("Sp A", "Other sp", "Other sp", "Other sp",
                             "Sp A", "Other sp", "Other sp"), 
                 Study = c("A", "A", "A", "A", 
                           "B", "B", "B"), 
                 Value = c(1, 3, 4, 5, 3, 6, 7))

# Split data
other <- df %>% filter(Species == "Other sp")
sp_a <- df %>% filter(Species == "Sp A")

# Recombine into the data set for plotting
df <- other %>%
  inner_join(sp_a, by = "Study")

# Make the plot
ggplot(df, aes(x = Species.y, y = Value.y)) +
  geom_segment(aes(xend = Species.x, yend = Value.x, colour = Study))

      



Multiple line segments optional.  Additional settings for labels, points, etc.  still needed

Adjust the schedule as desired!

+4


source


You can do this with geom_line

if for each level Study

you duplicate the number of lines Sp A

to match the number of lines Other sp

and then assign a unique ID to each pair Sp A

and Other sp

for aesthetics group

.

library(tidyverse)

df %>% group_by(Study) %>% 
  slice(c(rep(1,length(Species[Species=="Other sp"])),2:n())) %>%  
  group_by(Study, Species) %>% 
  mutate(ID = paste0(Study, 1:n())) %>% 
  ggplot(aes(y = Value, x=Species, group=ID, colour=Study)) + 
    geom_point(shape=1) +
    geom_line() +
    theme_bw()

      



enter image description here

+2


source







All Articles