Vladimir
Vladimir

Reputation: 748

How to plot only vertical lines of different colours over the date axis with geom_vline in Shiny?

I am a complete newbie to ggplot2. I have been trying to understand how to use aesthetics and geom_vline to do the following with no success. I presume there must be a simple and elegant solution to this in one line, but I can't get it.

So, I have a data frame with columns (dates, category, colour).

For example:

dates = c("1/Jan/2022 06:00", "1/Jan/2022 18:00", "2/Jan/2022 06:00", "2/Jan/2017 18:00")
category = c(1, 5, 6, 3)
colour = c("black", "red", "blue", "red")
data = data.frame(dates, category, colour)

The Y-axis is categorical, but could be continuous. I would like to plot vertical lines for each date on X-axis with specified colour and on Y-axis every line should go from category - 0.5 up to category + 0.5.

On X-axis I would like to observe only months on ticks, and on Y-axis all the categories. The data frame has thousands of dates- is there a risk of overlapping lines? Is there a way of controlling the line thickness using the pixel size of this plot in Shiny app and the total number of lines?

Any help is appreciated!

Upvotes: 1

Views: 80

Answers (1)

langtang
langtang

Reputation: 24877

I don't what your dates are, so I provide my own dates like this:

dates = seq.Date(as.Date("2022-01-01"), as.Date("2022-02-01"), length.out = 4)

Now, you can simply use geom_linerange, and I've invented a set of shiny-like inputs, just to give you a suggestion of how you might use information from user inputs from a shiny app to set the point and line width/size

input = list(linewidth=1, pointsize=2)

ggplot(data, aes(dates,category, color=colour)) + 
  geom_point(size=input$pointsize) + 
  geom_linerange(aes(ymin=category-0.5, ymax=category+0.5),size=input$linewidth)

geom_linerange

Upvotes: 1

Related Questions