Search code examples
rgraphdate-range

Graph showing data with from and to date ranges in r


I have following data of purchase and maturity of investments.

investment <- as.character(c("First", "Second", "Third"))
from <- as.Date(c("2019-11-01", "2020-02-25", "2020-06-10"))
to <- as.Date(c("2020-08-31","2021-02-24", "2020-08-09"))
amount <- as.numeric(c(20000,15000,17000))
df <- data.frame(investment, from, to, amount)

I want Horizontal Bars with Dates on X axis, minimum being the earliest date in the dataset i.e. "2019-11-01" and maximum being the last date "2021-02-24". investment on Y axis i.e. First, Second and Third.

Horizontal bars should appear between the dates as shown (from and to) against each investment, showing different investments covering different period on the X axis.

Mouse hover shall display amount as label. No relevance of amount on either X or Y axis.


Solution

  • You can do this with geom_linerange() from ggplot2

    library(ggplot2)
    ggplot(df) + 
      geom_linerange(aes(y = investment, xmin = from, xmax = to ), size = 18,
                     color = "orange") +
      xlab("date")
    

    enter image description here