Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a bar plot with lower and upper limits

Let say I have below plot

library(ggplot2)
library(zoo)
dat = rbind(data.frame('Quarter' = as.yearqtr(as.Date(c('2000-01-01', '2002-01-01', '2004-01-01', '2006-01-01'))), 'Val' = c(10,20,30,40), 'Val_Lower' = c(10,20,30,40) - 5, 'Val_Upper' = c(10,20,30,40)+5, type = rep('A', 4)), 
            data.frame('Quarter' = as.yearqtr(as.Date(c('2000-01-01', '2002-01-01', '2004-01-01', '2006-01-01'))), 'Val' = c(10,20,30,40)-5, 'Val_Lower' = c(10,20,30,40)-5 - 5, 'Val_Upper' = c(10,20,30,40)+5-5, type = rep('B', 4)))

ggplot(dat, aes(x = Quarter, y = Val)) +
  geom_point(aes(color = type)) +
  geom_ribbon(aes(fill = type, ymin = Val_Lower, ymax = Val_Upper), alpha = .3)

However instead of continuous ribbon for lower and upper limits, I want to have vertical bar for each dat separately with different type, something like below

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there any way to achieve this kind of plot?

>Solution :

We could use geom_linerange:

ggplot(dat, aes(x = Quarter, y = Val, color = type)) +
  geom_linerange(aes(ymin = Val_Lower, ymax = Val_Upper), 
                 alpha = .3, linewidth = 15) +
  geom_point()

Created on 2024-12-23 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading