Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

r - 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

question from:https://stackoverflow.com/questions/66066366/horizontal-percent-total-stacked-bar-chart-with-labels-on-each-end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...