SiH
SiH

Reputation: 1546

create outlines bars in bar graph ggplot

Below is a simple example. I wish to create an outline of the bar graph plot.

Below is an example how the desire plot looks like.

Outlines bars in bar graph ggplot

library(tidyverse)

level <- c("a", "b", "c", "d", "e", "f", "g")
value <- c(8.1, 5.6, 3.2, 4.4, 3.5, 2.5, 1.8)

tbl <- tibble(level = level, 
              value = value)

# create plot using geom_step() 
ggplot(data = tbl,
       aes(x = level, 
           y = value)) + 
  geom_step(col = "black") + 
  theme_bw()

Upvotes: 0

Views: 140

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173858

Modifying the linked answer to apply to your data frame, we get:

ggplot(tbl,
       aes(x = level, 
           y = value)) + 
  geom_col(width = 1, fill = "#e0a0e8", alpha = 0.5) +
  geom_step(data = tbl %>%
            mutate(level = as.numeric(factor(level)) - 0.5) %>%
            summarise(level = c(level[1], level, rep(last(level) + 1, 2)),
            value = c(0, value, last(value), 0)),
            aes(group = 1), col = "black") + 
  theme_bw(base_size = 20)

enter image description here

Upvotes: 2

Related Questions