Home > OS >  Outlines bars in bar graph ggplot
Outlines bars in bar graph ggplot

Time:09-17

I was wondering if there was a way to outline the bars in my bar graph. I wanted to outline the left, top, and right sides of a bar that is out a group of bars and then outline a group of bars that are clumped together. I have tried a bit with this but haven't had much luck. I am not entirely sure it is possible. I will attach some code for my data, graph, and some images of what I hope the graph will look like

library(ggplot2)
ggplot(df, aes(bar,num, fill = group))  
  geom_bar(stat = 'identity', width = 5)  
  scale_fill_manual(values = alpha(c("blue"), .3))

Here is the data

df <- structure(list(bar = c(17.5, 27.5, 32.5, 37.5, 42.5, 47.5, 52.5, 
57.5, 62.5, 67.5, 72.5, 77.5, 82.5), num = c(1L, 7L, 8L, 11L, 
22L, 46L, 43L, 60L, 59L, 40L, 17L, 11L, 1L), group = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "A", class = "factor")), class = "data.frame", row.names = c(NA, 
-13L))

This is what the graph currently looks likeenter image description here

and this is what I hope to make

enter image description here

CodePudding user response:

You can hack geom_step to do this by adding in the zero length bars.

zeroes <- setdiff(seq(min(df$bar), max(df$bar)   5, by = 5), df$bar)
df2 <- rbind(df, data.frame(bar = min(df$bar), num = 0, group = "A"))
df2 <- rbind(df2, data.frame(bar = zeroes, num = 0, group = "A"))
df2 <- df2 %>% arrange(bar, num)

library(ggplot2)
ggplot(df2, aes(bar,num, fill = group))  
  geom_bar(stat = 'identity', , width = 5)  
  geom_step(col = 'red', aes(x = bar - 2.5))  
  scale_fill_manual(values = alpha(c("blue"), .3))

enter image description here

  • Related