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

ggplot2 horizontal line for bar chart

I have following barchart drawn using ggplot2 in R. We would like to I would like to draw blue line for "Total" values. I tried using geom_linerange and geom_errorbar, but was not successful, how can I get the blue lines for hosrizantal bar chart?

enter image description here

dat=read.csv(textConnection(
  "Category,Value1,Value2,Total,Group
A,10,10,20,1
B,20,30,50,1
C,5,2,7,1
D,5,10,15,2
E,10,20,30,2
F,30,4,34,2"))

library(tidyverse)
library(ggplot2)

dat %>%
  arrange(desc(Group), Total) %>%
  mutate(Category = fct_inorder(Category)) %>%
  pivot_longer(Value1:Total) -> dat2

ggplot(filter(dat2, !name %in% c("Value2","Total")),
       aes(value, Category, label = value)) +
  geom_col(aes(fill = name), position = position_stack(reverse = TRUE)) +
  geom_text(position = position_stack(vjust = 0.5, reverse = TRUE))  +
  geom_text(data = filter(dat2, name == "Total"),
            hjust = -0.5

)

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

>Solution :

You can achieve your desired result using a geom_segment where for the y and yend aes you have to convert Category to a numeric and shift by +/- the half bar width which by default is .9 / 2 = .45:

library(ggplot2)

ggplot(
  dplyr::filter(dat2, !name %in% c("Value2", "Total")),
  aes(value, Category, label = value)
) +
  geom_col(aes(fill = name), position = position_stack(reverse = TRUE)) +
  geom_segment(
    data = filter(dat2, name == "Total"),
    aes(
      xend = value,
      y = as.numeric(factor(Category)) - .45,
      yend = as.numeric(factor(Category)) + .45
    ),
    color = "blue"
  ) +
  geom_text(position = position_stack(vjust = 0.5, reverse = TRUE)) +
  geom_text(
    data = filter(dat2, name == "Total"),
    hjust = -0.5
  )

enter image description here

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