Prabesh
Prabesh

Reputation: 40

Plotting a line between two points in a datapoint in R ggplot

So I have a data that looks something like this.

User | Start | End
A    |  1    | 3
B    |  2    | 5
C    |  1    | 3
D    |  4    | 5
E    |  3    | 4
F    |  1    | 5

Now using ggplot2, I want to make a graph that looks something like the following. enter image description here

I have tried using geom_line() and geom_tile() but I cannot seem to figure it out.

Upvotes: 2

Views: 1050

Answers (3)

akrun
akrun

Reputation: 887851

We can use

library(ggplot2)
library(dplyr)
df1 %>%
    mutate(rn = row_number()) %>%
    ggplot() + 
      geom_segment(aes(x = rn, y = User, xend = End, yend = User, col = User))
`` 

Upvotes: 1

Uwe
Uwe

Reputation: 42582

The package has a geom_dumbbell() function. The data can be used as is, no pivoting is required.

library(ggalt)
ggplot(df1, aes(x = Start, xend = End, y = User)) + 
  geom_dumbbell()

enter image description here

The plot can be customised to simulate OPs expected result:

ggplot(df1, aes(x = Start, xend = End, y = User)) + 
  geom_dumbbell(size = 1, shape = 1, size_x = 2.5, size_xend = 2.5, stroke = 1.5) +
  scale_y_discrete(limits = rev, labels = NULL) +
  xlab(NULL) +
  theme_classic()

enter image description here

Please, note that the direction of the y axis has changed: User A to F runs from top to bottom as requested.

geom_dumbbell() can be further customised to simulate the color scheme of Ronak's answer:

pal <- scales::hue_pal()(2)
ggplot(df1, aes(x = Start, xend = End, y = User)) + 
  geom_dumbbell(size = 1, colour = pal[2], size_x = 2.5, 
                size_xend = 2.5, colour_xend = pal[1], stroke = 1.5) +
  scale_y_discrete(limits = rev, name = NULL) +
  xlab(NULL) +
  theme_classic()

enter image description here

Data

df1 <- data.table::fread(
"User | Start | End
A    |  1    | 3
B    |  2    | 5
C    |  1    | 3
D    |  4    | 5
E    |  3    | 4
F    |  1    | 5")

Upvotes: 3

Ronak Shah
Ronak Shah

Reputation: 389235

Here's one way to do this -

library(tidyverse)

df %>% 
  pivot_longer(cols = -User) %>%
  ggplot(aes(x= value, y= User, group = User, color = name)) +
  geom_line()+
  geom_point(size=4) +
  theme_classic()

enter image description here

data

df <- structure(list(User = c("A", "B", "C", "D", "E", "F"), Start = c(1L, 
2L, 1L, 4L, 3L, 1L), End = c(3L, 5L, 3L, 5L, 4L, 5L)), 
class = "data.frame", row.names = c(NA, -6L))

Upvotes: 4

Related Questions