MNU
MNU

Reputation: 764

How to make side by side vertical segment in r

With the following data set

set.seed(1)
mydf=data.frame(slno=c(1:5), x1=rnorm(5),x2=rnorm(5))
> mydf
  slno         x1         x2
1    1 -0.6264538 -0.8204684
2    2  0.1836433  0.4874291
3    3 -0.8356286  0.7383247
4    4  1.5952808  0.5757814
5    5  0.3295078 -0.3053884

How can I make the vertical line segment for each row. I should have 5 side by side vertical line. For row 1 (slno=1), vertical line will start from -0.0626 to -0.82046 and so on. Any help is appreciated

Upvotes: 0

Views: 220

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388982

You can try reshaping the data and then use geom_line :

library(tidyverse)

tidyr::pivot_longer(mydf, cols = -slno) %>%
  ggplot() + aes(slno, value, group = slno) + geom_line()

enter image description here

Same plot when resized :

enter image description here

Upvotes: 1

andrew_reece
andrew_reece

Reputation: 21274

You can use ggplot2::geom_segment:

library(ggplot2)

ggplot(mydf) +
  geom_segment(aes(x = slno, xend = slno, y = x1, yend = x2))

enter image description here

Upvotes: 3

Related Questions