Miguel Angel Arnau
Miguel Angel Arnau

Reputation: 161

Plotting lines in ggplot2

Is it possible to make this graph with ggplot, ordering the graph by the variable "t" in ascending order, distinguishing each "t" according to status (black or white circle, it can be another marker...) and if possible the variable "id " on the ordinate axis.

Id<- c(1,2,3,4)
t<- c(10,5,20,15)
status<- c(0,1,0,1)
df<- data.frame(Id, t, status)

enter image description here

Upvotes: 2

Views: 47

Answers (1)

Quinten
Quinten

Reputation: 41225

Maybe you want something like this using geom_segment for the lines with geom_vline for the vertical lines. Using shape and fill aesthetics to fill the points with "black" and "white" per status. You can use the following code:

Id<- c(1,2,3,4)
t<- c(10,5,20,15)
status<- c(0,1,0,1)
df<- data.frame(Id, t, status)

library(ggplot2)
library(dplyr)
library(forcats)
df %>%
  mutate(Id = as.factor(Id),
         status = as.factor(status)) %>%
  ggplot(aes(x = t, y = fct_reorder(Id, t, .desc = TRUE), shape = status, fill = status)) +
  geom_point() +
  geom_segment(aes(x = 0, xend = t, y = Id, yend = Id)) +
  geom_vline(xintercept=c(t),linetype="dotted", alpha = 0.4) +
  scale_shape_manual(values=c(21, 21), name = "shapes!") +
  scale_fill_manual(values=c("black", "white")) +
  scale_x_continuous(expand = c(0, 0), limits = c(0, 25)) + 
  labs(x = "", y = "Id") +
  theme_bw() +
  theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        legend.position = "none",
        axis.title.y = element_text(angle=0)) 

Created on 2022-07-25 by the reprex package (v2.0.1)

Upvotes: 2

Related Questions