DJC
DJC

Reputation: 1611

Horizontal percent total stacked bar chart with labels on each end

I have a simple data frame which has the probabilities that an id is real and fake, respectively:

library(tidyverse)
dat <- data.frame(id = "999", real = 0.7, fake = 0.3)

I know that I can show this as a horizontal bar chart using the code below:

dat %>% 
  gather(key = grp, value = prob, -id) %>% 
  ggplot(aes(x = id, y = prob, fill = grp)) +
  geom_bar(stat = "identity") +
  coord_flip()

enter image description here

But I was wondering if there was a way to show this in the same way as shown below, with the class labels and probabilities on either end of the bar chart?

enter image description here

Many thanks

Upvotes: 1

Views: 228

Answers (2)

tjebo
tjebo

Reputation: 23737

A straight forward, maybe somewhat cheeky workaround is to re-define your 0.

I added a few calls that are not strictly necessary, but make it look closer to your example plot.

library(tidyverse)
dat <- data.frame(id = "999", real = -0.7, fake = 0.3) # note the minus sign!

dat %>% 
  gather(key = grp, value = prob, -id) %>% 
  ggplot(aes(x = id, y = prob, fill = grp)) +
  geom_col(show.legend = FALSE) + 
  geom_text(aes(label = stringr::str_to_title(paste0(grp, " (", as.character(100*abs(prob)), "%)"))), 
            hjust = c(1,0))+
  coord_flip(clip = "off") +
  scale_fill_brewer(palette = "Greys") +
  theme_void() +
  theme(aspect.ratio = .1,
        plot.margin = margin(r = 3, l = 3, unit = "lines"))

Created on 2021-02-06 by the reprex package (v0.3.0)

Upvotes: 2

Zero Pancakes
Zero Pancakes

Reputation: 296

I'm not sure this fully answers the question but I think it will improve the plot, can you try it out?

dat %>% 
  gather(key = grp, value = prob, -id) %>% 
  ggplot(aes(x = id, y = prob, fill = grp)) +
  geom_bar(stat = "identity", position = "fill") +
  scale_y_continuous("Proportion") +
  scale_x_discrete("", expand = c(0,0)) +
  scale_fill_identity() +
  coord_flip()

Upvotes: 1

Related Questions